我试图将权限数据提取到我的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": []
},
但我没有"权限"
答案 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' )