我创建了3个小组:1.职员,2. Admin,3. Operational Manager,并分配了权限。现在,无论何时我想添加新用户,我都希望显示组的选择字段并能够选择组。
根据框架,用户和组具有多对多关系,我正在尝试实现嵌套序列化器。根据添加嵌套数据的文档,我需要在序列化程序中实现create
或update
方法,但是在这里我没有得到group中的choice字段,并且数据为null。
GroupSerializer:
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('name',)
UserSerializers:
class UserSerializers(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
class Meta:
model = User
fields = ('first_name', 'last_name','address','contact', 'email', 'date_of_birth', 'branch', 'groups')
def create(self, validated_data):
groups_data = validated_data.pop('groups')
user = User.objects.create(**validated_data)
for group_data in groups_data:
Group.objects.create(user=user, **group_data)
return user
当我想要发帖时,我会得到:
{
"first_name": "",
"last_name": "",
"address": "",
"contact": null,
"email": "",
"date_of_birth": null,
"branch": null,
"groups": []
}
此处分组字段为空。 如果我尝试发布帖子,它会显示
{
"groups": [
"This field is required."
]
}
编辑:已解决
我删除了GroupSerializer
是因为User
模型与Group
有多对多关系,因此我们无需显式指定Group
对象
# class GroupSerializer(serializers.ModelSerializer):
# class Meta:
# model = Group
# fields = ('name',)
class UserSerializers(serializers.ModelSerializer):
# groups = GroupSerializer(many=True)
class Meta:
model = User
fields = ('username','first_name', 'last_name','address','contact', 'email', 'date_of_birth', 'branch', 'groups')
def create(self, validated_data):
groups_data = validated_data.pop('groups')
user = User.objects.create(**validated_data)
for group_data in groups_data:
# Group.objects.create(user=user, **group_data)
user.groups.add(group_data)
return user
答案 0 :(得分:0)
您可以使用PrimarykeyRelatedField
并提供要添加到列表中的组的ID。如下所示:
class UserSerializers(serializers.ModelSerializer):
groups = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all())
class Meta:
model = User
fields = ('first_name', 'last_name', 'address', 'contact', 'email', 'date_of_birth', 'branch', 'groups')
def create(self, validated_data):
groups_data = validated_data.pop('groups')
user = User.objects.create(**validated_data)
for group_data in groups_data:
Group.objects.create(user=user, **group_data)
return user
def to_representation(self, instance):
r = super(UserSerializers, self).to_representation(instance)
r.update({
'groups': GroupSerializer(many=True).to_representation(instance.groups)
})
return r
因此只需提供如下的组列表:"groups": [1,2,3]
,如果您想在响应中对每个组的json结果进行序列化,则还应该重写to_representation
方法。