gpt4 book ai didi

python - Django RF 可写嵌套序列化器

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:43 26 4
gpt4 key购买 nike

我正在尝试在 DRF3 中制作一个可写的嵌套序列化器。我有一个模型音乐会,其中有一个 m2m 领域“技术人员”到我的用户模型。我已成功在其 View 中添加连接到 Concert 实例的用户列表。现在我希望能够将技术人员/用户添加到 Concert 模型中。

这是我到目前为止的序列化器:

class ConcertListSerializer(serializers.ModelSerializer):
technicians = UserDetailSerializer(
many=True,
read_only=True
)

class Meta:
model = models.Concert
fields = [
'name',
'date',
'technicians',
'id',
]

def create(self, validated_data):
# list of pk's
technicians_data = validated_data.pop('technicians')
concert = Concert.object.create(**validated_data)

for tech in technicians_data:
tech, created = User.objects.get(id = tech)
concert.technicians.add({
"name": str(tech.name),
"email": str(tech.email),
"is_staff": tech.is_staff,
"is_admin": tech.is_admin,
"is_superuser": tech.is_superuser,
"groups": tech.groups,
"id": tech.id
})
return concert

我希望能够添加我想要添加的技术人员的 pk/id 列表。例如:

"technicians": [1,2,3]

将用户 1、2、3 添加到 Concert 的技术人员字段中。

每当我这样做时,我都会收到 KeyError,只显示“技术人员”并引用我的 create() 函数中的第一行...

我在字典中添加的字段都是用户模型的字段。这是我执行 GET 请求时显示的格式。

这是音乐会模型:

class Concert(models.Model):
name = models.CharField(max_length=255)
date = models.DateTimeField(default =
datetime.now(pytz.timezone('Europe/Oslo'))
+ timedelta(days=30)
)
technicians = models.ManyToManyField(User) # relation to user model

编辑:这是预制示例音乐会上 GET 请求的响应:

{
"name": "Concert-name",
"date": "2017-10-28T12:11:26.180000Z",
"technicians": [
{
"name": "",
"email": "test2@test.com",
"is_staff": true,
"is_admin": true,
"is_superuser": false,
"groups": [
5
],
"id": 2
},
{
"name": "",
"email": "test3@test.com",
"is_staff": true,
"is_admin": true,
"is_superuser": false,
"groups": [
5
],
"id": 3
}
],
"id": 1
}

最佳答案

您应该从上下文请求中获取数据,因为您提交的数据是只读的,validated_data 中缺少它

def create(self, validated_data):
# list of pk's
# instaed of technicians_data = validated_data.pop('technicians')
# use next two lines
request = self.context.get('request')
technicians_data = request.data.get('technicians')

concert = Concert.object.create(**validated_data)

# Added technicians
for tech in technicians_data:
user = User.objects.get(id=tech)
concert.technicians.add(user)

return concert

关于python - Django RF 可写嵌套序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com