Django rest framework serializing many to many field

前端 未结 7 1460
旧时难觅i
旧时难觅i 2020-11-28 03:46

How do I serialize a many-to-many field into list of something, and return them through rest framework? In my example below, I try to return the post together with a list of

7条回答
  •  一整个雨季
    2020-11-28 04:22

    The default ModelSerializer uses primary keys for relationships. However, you can easily generate nested representations using the Meta depth attribute:

    class PostSerializer(serializers.ModelSerializer):
        class Meta:
            model = Post
            fields = ("text", "tag")
            depth = 1 
    

    As mentioned in the documentation :

    The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.

提交回复
热议问题