Django Rest Framework可选的嵌套关系

时间:2019-03-07 14:48:30

标签: python django django-rest-framework

是否可以使用嵌套关系序列化程序作为选项?这是来自文档的序列化器示例:

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__'

当我呼叫相册列表localhost:8000/album/1/时,这是响应:

{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
        ...
    ],
}

是否有类似localhost:8000/album/1/?include=tracks这样的选项,因此仅在include参数中声明音轨数据时才会显示。

2 个答案:

答案 0 :(得分:1)

一个例子

class OrderSerializer(ModelSerializer):
    payments = PaymentSerializer(many=True, read_only=True)
    evaluations = OrderEvaluationSerializer(many=True, read_only=True)

    def __init__(self, *args, **kwargs):
        super(OrderSerializer, self).__init__(*args, **kwargs)

        request = kwargs['context']['request']
        include_address = request.GET.get('include_address', False)  # <<<---

        if include_address:  # <<<---
            self.fields['user_location'] = UserLocationSerializer(read_only=True, context=kwargs['context'])  # <<<---

从这里:http://masnun.com/2015/10/21/django-rest-framework-dynamic-fields-in-serializers.html

答案 1 :(得分:0)

您可以使用drf-dynamic-fields软件包。通过传递如下网址参数,将其用于动态包含字段:

GET /identities

[
  {
    "id": 1,
    "url": "http://localhost:8000/api/identities/1/",
    "type": 5,
    "data": "John Doe"
  },
  ...
]

另一方面,带有fields参数的查询仅返回一部分字段:

GET /identities/?fields=id,data

[
  {
    "id": 1,
    "data": "John Doe"
  },
  ...
]

使用omit参数进行的查询会排除指定的字段。

GET /identities/?omit=data

[
  {
    "id": 1,
    "url": "http://localhost:8000/api/identities/1/",
    "type": 5
  },
  ...
]