Skip to content

Use 'source' to determine which fields should be autogenerated #93

@Philipp-Userlike

Description

@Philipp-Userlike

It would be nice if one could use 'source' to change the name of a field in serialized data:

class MyModel(models.Model):
    id = models.AutoField(primary_key=True)


@dataclass
class MyDataclass:
    model: MyModel


class MyDataclassSerializer(DataclassSerializer):
    model_id = PrimaryKeyRelatedField(queryset=MyModel.objects.all(), source="model")

    class Meta:
        dataclass = MyDataclass

Right now this autogenerates another related field with the name 'model' and expects both to be in the serializer input data.

MyDataclassSerializer(data={"model_id": 1}).is_valid(raise_exception=True)
# raises rest_framework.exceptions.ValidationError: {'model': [ErrorDetail(string='This field is required.', code='required')]}

As a workaround I have to exclude the original like this:

class MyDataclassSerializer(DataclassSerializer):
    model_id = PrimaryKeyRelatedField(queryset=MyModel.objects.all(), source="model")

    class Meta:
        dataclass = MyDataclass
        exclude = ["model"]

Our use case is that we have both references and subserialized objects in our API, and we use '_id' as a postfix to identify references.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions