Django Rest framework serializer exclude foreign key with depth 2

前端 未结 2 964
野的像风
野的像风 2021-01-19 09:00

I have made an api that returns an object as json data. I Am using the django-rest-framework and its serializer. Using the resources (ModelResource) I excluded some fields,

相关标签:
2条回答
  • 2021-01-19 09:38

    Here is how an other solution could be.

    class ProToPicturesSerial(serializers.ModelSerializer):
        pro_pictures = PictureSerializer(many=True)
        pro_videos = VideoSerializer(many=True)
        city_pro = CitySerializer(many=True)
    
        class Meta:
            model = Province
            fields = ('id', 'name', 'intro', 'description', 'display_url', 'pro_pictures', 'pro_videos', 'city_pro')
    
    0 讨论(0)
  • 2021-01-19 09:41

    Ah, i just found it:

    I need to add in the resource for all fields I want to show what resource....

    fields = ('name', ("parent","MyObjectResource") , 'and all the other fields you want to see as well...')

    I found it here: google groups forum question

    You can skip the exlude, it ignores it, and just add the fields you want to show, you do not have to define them, unless you need to indicate what resource to use.

    So following is the final code of the resource.py part:

    class MyObjectResource(ModelResource):
        model = MyObject
        fields = ('name', ("parent","MyObjectResource"), 'and all the other fields you want to see as well...')
    
    0 讨论(0)
提交回复
热议问题