合并django-rest-framework结果

时间:2017-07-07 14:06:59

标签: django django-rest-framework

我正在制作我的第一个API,这几乎就是我想要的。我正在努力为用户提供单独访问和通过他们的组访问,但我想设置API以显示用户明确的所有访问权限,而不是将其嵌入到组中。

基本上,我想采用group_affiliation结果并将它们合并到其余的结果中,因为它们具有相同的结构,并且更容易以该格式使用。

目前,我的输出如下:

[
    {
        "username": "admin",
        "access": [
            {
                "name": "foo"
            },
            {
                "name": "bar"
            }
        ],
        "group_affiliation": [
            {
                "access": [
                    {
                        "name": "eggs"
                    },
                    {
                        "name": "foo"
                    }
                ],
            },
        ]
    },
]

但我希望它看起来更像这样,其中group_affiliation结果合并到其他结果中:

[
    {
        "username": "admin",
        "access": [
            {
                "name": "foo"
            },
            {
                "name": "bar"
            },
            {
                "name": "eggs"
            }
        ],
    }
]

这是我的models.py:

class Access(models.Model):
    name = models.CharField(max_length=100)
    site_user_access = models.ManyToManyField(User, blank=True)
    site_group_access = models.ManyToManyField(Group, blank=True)

这是我的serializers.py:

class AccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = TopAccess
        fields = ('name', )


class GroupSerializer(serializers.ModelSerializer):
    access = AccessSerializer(
            source='access_set',
            many=True
            )

    class Meta:
        model = Group
        fields = (
                'access',
                )


class UserAccessSerializer(serializers.ModelSerializer):
    access = AccessSerializer(
            source='access_set',
            many=True
            )
    group_affiliation = GroupSerializer(
            source='groups',
            many=True,
            )

    class Meta:
        model = User
        fields = (
                'username',
                'access',
                'group_affiliation',
                )

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

感谢@ zaphod100.10和Betelgeuse V的用户指出我正确的方向以及其他post给我的语法。

这是我的解决方案:

class AccessSerializer(serializers.ModelSerializer):
    class Meta:
        model = Access
        fields = ('name', )


class UserAccessSerializer(serializers.ModelSerializer):
    access = SerializerMethodField('access_set')

    class Meta:
        model = User
        fields = (
                'username',
                'access',
                )

    def access_set(self, user):
        queryset = Access.objects.filter(site_user_access=user)
        queryset = queryset | Access.objects.filter(site_group_access__user=user)
        queryset = queryset.distinct()
        serializer = AccessSerializer(instance=queryset, many=True)
        return serializer.data

上面列出了所需的结果