Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update_or_create_reverse_relations does not set parent on sub-serializers #28

Open
MattFisher opened this issue Nov 13, 2017 · 1 comment
Labels

Comments

@MattFisher
Copy link

I have a use case where I need to customise the create method of a nested serializer, because the model it creates depends on a field in the parent serializer.
If I override create(self, validated_data), self.parent (and self.root) are None within the method body. Normally self.parent and some other fields are set in rest_framework.fields.Field.bind() when the serializer is initially defined, but because update_or_create_reverse_relations creates a new serializer for the nested field, rather than mutating values on the existing one, these fields don't get set.

The simplest fix would be to add serializer.parent = self in one of two places indicated below, but I don't know whether there would be unintended side effects.

Another option would be to change the instance and/or data values on the the existing serializer (field in the code below) rather than creating a new one, but I presume there were side-effects from this that led to the current approach in the first place.

Within BaseNestedModelSerializer.update_or_create_reverse_relations:

for data in related_data:
    obj = instances.get(
        self._get_related_pk(data, field.Meta.model)
    )
    serializer = self._get_serializer_for_field(
        field,
        instance=obj,
        data=data,
    )
    # serializer.parent = self  # <== possibly add this here?
    serializer.is_valid(raise_exception=True)
    related_instance = serializer.save(**save_kwargs)

# elsewhere in BaseNestedModelSerializer
def _get_serializer_for_field(self, field, **kwargs):
    kwargs.update({
        'context': self.context,
        'partial': self.partial,
    })
    serializer = field.__class__(**kwargs)
    # serializer.parent = self  # <== alternatively add this here?
    return serializer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants