本文介绍了如何在Django Rest Framework嵌套序列化程序中动态更改深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组嵌套的序列化器,在它们各自的 Meta 类上设置了 depth 。我想基于视图中传递的参数以编程方式更改深度。

I have a set of nested serializers which have a depth set on their respective Meta classes. I'd like to programmatically change the depth based on parameters passed into in views.

class ResourceSerializer(serializers.ModelSerializer):
    type         = serializers.PrimaryKeyRelatedField(queryset=EntityType.objects.all())
    tags         = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True)

    class Meta:
        model  = Resource
        fields = ('id', 'type', 'uri', 'tags', 'created_date')
        depth = 1

不幸的是,似乎没有一种方法可以覆盖深度在运行时属性。我当前的解决方案是继承浅序列化程序并重写其Meta类以调整深度。

Unfortunately, there doesn't seem to be a way to override the depth attribute at runtime. My current solution has been to inherit the "shallow" serializers and override their Meta classes to adjust the depth.

class ResourceNestedSerializer(ResourceSerializer):
    class Meta(ResourceSerializer.Meta):
        depth = 2

在我看来:

    if nested:
        serializer = ContainerNestedSerializer(containers, many=True)
    else:
        serializer = ContainerSerializer(containers, many=True)
    return Response(serializer.data)

在调用 serializer.data 之前有什么方法可以调整深度

Is there any way to adjust depth before calling serializer.data?

推荐答案

这是我的代码,其中包含了包括/排除字段以及动态调整深度。根据您的口味进行调整。 :)

Here is my code that incorporates including/excluding fields, as well as dynamically adjusting the depth. Adjust it to your taste. :)

class DynamicModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed, and takes in a "nested"
argument to return nested serializers
"""

def __init__(self, *args, **kwargs):
    fields = kwargs.pop("fields", None)
    exclude = kwargs.pop("exclude", None)
    nest = kwargs.pop("nest", None)

    if nest is not None:
        if nest == True:
            self.Meta.depth = 1

    super(DynamicModelSerializer, self).__init__(*args, **kwargs)

    if fields is not None:
        # Drop any fields that are not specified in the `fields` argument.
        allowed = set(fields)
        existing = set(self.fields.keys())
        for field_name in existing - allowed:
            self.fields.pop(field_name)

    if exclude is not None:
        for field_name in exclude:
            self.fields.pop(field_name)

这篇关于如何在Django Rest Framework嵌套序列化程序中动态更改深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:16