Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?

前端 未结 7 2076
Happy的楠姐
Happy的楠姐 2020-12-01 05:09

I have two models, one with M2M relation and a related name. I want to include all fields in the serializer and the related field.

models.py:

<
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 05:47

    The fields="__all__" option can work by specifying an additional field manually as per the following examples. This is by far the cleanest solution around for this issue.

    Nested Relationships

    http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

    class TrackSerializer(serializers.ModelSerializer):
        class Meta:
            model = Track
            fields = '__all__'
    
    class AlbumSerializer(serializers.ModelSerializer):
        tracks = TrackSerializer(many=True, read_only=True)
    
        class Meta:
            model = Album
            fields = '__all__'
    

    I would assume this would work for any of the other related field options listed on the same page: http://www.django-rest-framework.org/api-guide/relations/#serializer-relations

    Reverse relation example

    class TrackSerializer(serializers.ModelSerializer):
        album = AlbumSerializer(source='album_id')
    
        class Meta:
            model = Track
            fields = '__all__'
    

    Note: Created using Django Rest Framework version 3.6.2, subject to change. Please add a comment if any future changes break any examples posted above.

提交回复
热议问题