yezyilomo / django-restql

Turn your API made with Django REST Framework(DRF) into a GraphQL like API.
https://yezyilomo.github.io/django-restql
MIT License
620 stars 43 forks source link

Question about NestedModelSerializer #131

Closed daidaitaotao closed 4 years ago

daidaitaotao commented 4 years ago

Hello,

I recently encounter an issue with using NestedModelSerializer for updating a nested field. I am wondering if it is a bug.

For example, I have the nested serializer set up this way:

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ["id", "city", "country"]

class PropertySerializer(NestedModelSerializer):
    location = NestedField(LocationSerializer, required=False, allow_null=True)
    ..... other fields

I could create a property object through PropertySerializer without pass in a location data due to the fact that is not required.

Later on, I decided to patch a location into this property with request payload like

"location": {
        "city": "Newyork",
        "country": "USA"
  }

I noticed the location object has been created but it is not attached to the property.

I did a little research and found out it may be related to some logic in django_restql.mixins.NestedUpdateMixin.update_writable_foreignkey_related.

            nested_obj = getattr(instance, field)
            serializer = serializer_class(
                nested_obj,
                **kwargs,
                data=values,
                context=self.context,
                partial=serializer.is_partial
            )
            serializer.is_valid()
            if values is None:
                setattr(instance, field, None)
                objs.update({field: None})
            else:
                obj = serializer.save()
                objs.update({field: nested_obj})

In this code above, if the nested_obj did not exist, it will not attach the newly created obj back to instance. I wonder if it has been done intentionally? If so, I wonder what is the reason, and is there a proper way to patch a nested object into a parent object that did not originally exist?

Thank you!

yezyilomo commented 4 years ago

Thanks @daidaitaotao for pointing this out, it's definitely a bug, I guess I forgot to handle this case.

yezyilomo commented 4 years ago

Thanks for hunting it down too you made it so easy for me to fix it.

daidaitaotao commented 4 years ago

Hi, @yezyilomo thank you for the quick reply and thank you for helping us.