如何从不同的Serializer类中提取其他序列化数据?

时间:2018-01-11 20:04:55

标签: python django django-rest-framework

我试图将权限数据提取到我的UserSerializer中。我与User to Group有一个多对多关系,带有一个名为GroupUser的直通表。我能够提取group_id和group_name,但我似乎无法将数据填充到我的用户序列化程序中。 到目前为止,我已尝试使用permission = serializers.ReadOnlyField(source='group.permissions'),但这不起作用。

有什么建议吗?

这是我的代码:

class GroupSerializer(serializers.ModelSerializer):
    users = GroupUserSerializer(source='groupuser_set', many=True)
    permissions = PermissionSerializer(source='permission_set', many=True)
    class Meta:
        model = Group
        fields = ('id', 'name', 'users', 'permissions', 'role', )

class GroupUserSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='group.id')
    name = serializers.ReadOnlyField(source='group.name')
    class Meta:
        model = GroupUser
        fields = ( 'id', 'name', )

class UserSerializer(serializers.ModelSerializer):
     tests = TestSerializer(source='test_set', many=True)
     groups = GroupUserSerializer(source='groupuser_set', many=True)
     class Meta:
        model = User
        fields = ( 'id', 'username', 'groups', 'tests', )

我希望我的数据看起来像这样:

    {
    "id": 1,
    "username": "user",
    "groups": [
        {
            "id": 2,
            "name": "employee"
            "permission": "Access-Denied"
        }
    ],
    "tests": []
},

但我没有"权限"

2 个答案:

答案 0 :(得分:0)

class UserSerializer(serializers.ModelSerializer):
     tests = TestSerializer(source='test_set', many=True)
     groups = GroupSerializer(read_only=True, many=True)
     class Meta:
        model = User
        fields = ( 'id', 'username', 'groups', 'tests', )

编辑说明: 我能够通过一点修修补补找到答案。 我想,通过阅读docs和stackoverflow问题,你必须在引用多对多关系时包含'Through'表,但事实并非如此,序列化器已经为你做了。 因此,如图所示,我添加了这些信息组,并且GroupSerializer中与数据关系相关的所有数据都按照我希望的方式填充。

答案 1 :(得分:0)

我建议你为UserSerializer编写一个新的Serializer,这不会影响其他的Serializer:

class GroupForUserSerializer(serializers.ModelSerializer):
    users = GroupUserSerializer(source='groupuser_set', many=True)
    permissions = PermissionSerializer(read_only=True , many=True)
    class Meta:
        model = Group
        fields = ('id', 'name', 'permissions' )

然后您可以在UserSerializer现在使用GroupForUserSerializer

class UserSerializer(serializers.ModelSerializer):
     tests = TestSerializer(source='test_set', many=True)
     groups = GroupForUserSerializer(source='groupuser_set', many=True)
     class Meta:
        model = User
        fields = ( 'id', 'username', 'groups', 'tests' )