Django Rest框架中嵌套序列化器中的反向关系

时间:2018-11-27 09:48:22

标签: django django-rest-framework

我的models.py如下:

class Group(models.Model):
    name = models.CharField(max_length=50, unique=True)

class Policy(models.Model):
    name =  models.CharField(max_length=50, unique=True)
    source_group =  models.ForeignKey(Group, related_name='source_group')
    destination_group = models.ForeignKey(Group, related_name='destination_group')

由于我有两个指向同一模型的外键,因此我在使用相关名称以避免冲突。

现在,当我尝试为组创建序列化程序以列出与之关联的所有策略时,我将执行以下操作:

class PolicySerializer(serializers.ModelSerializers):
    class Meta:
         model = Policy
         fields = "__all__"

class GroupSerializer(serializers.ModelSerializer):
    policy = PolicySnippetSerializer(source ='source_group', many=True)

    class Meta:
        model = Group
        fields = ['id', 'name', 'policy']

但是,这只会给我一个source_group的策略。我如何获得与组,源和目标关联的所有组?

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点。

  1. 使用SerializerMethodField
  2. 通过覆盖data属性方法并将destination_group数据附加到policy键中。

方法1

class GroupSerializer(serializers.ModelSerializer):
    policy = serializers.SerializerMethodField()

    def get_policy(self, obj):
        source_groups = PolicySnippetSerializer(obj.source_group.all(), many=True).data
        destination_groups = PolicySnippetSerializer(obj.destination_group.all(), many=True).data

        return source_groups + destination_groups
# rest of the code

方法2

class GroupSerializer(serializers.ModelSerializer):
    policy = PolicySnippetSerializer(source ='source_group', many=True)

    @property
    def data(self):
        serializer_data = super().data()
        serializer_data['policy'] += PolicySnippetSerializer(self.instance.destination_group.all(), many=True).data

        return serializer_data

# rest of the code