Django Rest Framework - Read nested data, write integer

前端 未结 4 869
轻奢々
轻奢々 2021-01-01 14:39

So far I\'m extremely happy with Django Rest Framework, which is why I alsmost can\'t believe there\'s such a large omission in the codebase. Hopefully someone knows of a wa

4条回答
  •  清酒与你
    2021-01-01 15:33

    If you are using DRF 3.0 you can implement the new to_internal_value method to override the item field to change it to a PrimaryKeyRelatedField to allow the flat writes. The to_internal_value takes unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data. See the docs: http://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data

    So in your case it would be:

    class ItemSerializer(ModelSerializer):
        class Meta:
            model = Item
    
    class PinSerializer(ModelSerializer):
        item = ItemSerializer() 
    
        # override the nested item field to PrimareKeyRelatedField on writes
        def to_internal_value(self, data):
             self.fields['item'] = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
             return super(PinSerializer, self).to_internal_value(data)
    
        class Meta:
            model = Pin
    

    Two things to note: The browsable web api will still think that writes will be nested. I'm not sure how to fix that but I only using the web interface for debug so not a big deal. Also, after you write the item returned will have flat item instead of the nested one. To fix that you can add this code to force the reads to use the Item serializer always.

    def to_representation(self, obj):
        self.fields['item'] = ItemSerializer()
        return super(PinSerializer, self).to_representation(obj)
    

    I got the idea from this from Anton Dmitrievsky's answer here: DRF: Simple foreign key assignment with nested serializers?

提交回复
热议问题