gpt4 book ai didi

python - DRF 3 - 使用表创建多对多更新/创建序列化程序

转载 作者:太空狗 更新时间:2023-10-29 17:14:37 27 4
gpt4 key购买 nike

我正在尝试在 DRF 3 中创建一个引用应用程序来演示可以创建/更新模型的嵌套序列化程序。在尝试创建嵌套模型时,下面的示例代码用“*create() argument after ** must be a mapping, not list*”轰炸。我也不清楚我将如何处理 .update(),因为在某些情况下我只想建立额外的关系(人)。

示例模型:

from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
persons = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)

以及序列化器和 View 集:

from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet
from app.models import Group, Person
class PersonSerializer(ModelSerializer):
class Meta:
model = Person
class GroupSerializer(ModelSerializer):
persons = PersonSerializer(many=True)
def create(self, validated_data):
persons = validated_data.pop('persons')
group = Group.objects.create(**validated_data)
if persons: # Bombs without this check
Person.objects.create(group=group, **persons) # Errors here
return group
class Meta:
model = Group

class PersonModelViewSet(ModelViewSet):
serializer_class = PersonSerializer
queryset = Person.objects.all()

class GroupModelViewSet(ModelViewSet):
serializer_class = GroupSerializer
queryset = Group.objects.all()

我正在尝试发布一些 JSON,插入一个包含两个(相关)人员的组:

{
"persons": [
{ "name" : "name 1" },
{ "name" : "name 2" }
],
"name": "group name 1"
}

最佳答案

我不知道是否有更简单的方法,但我设法让它工作的唯一方法是在组序列化程序中引用“直通”模型“成员资格”,并为 .create() 和编写自定义代码。更新()。这似乎只是设置 M2M FK 的大量工作。如果有人知道更好的方法,我很乐意听到。

class GroupMembershipSerializer(ModelSerializer):
class Meta:
model = Membership
fields = ('person',)

class GroupCreateSerializer(ModelSerializer):
memberships = GroupMembershipSerializer(many=True, required=False)

def create(self, validated_data):
person_data = validated_data.pop('memberships')
group = Group.objects.create(**validated_data)
for person in person_data:
d=dict(person)
Membership.objects.create(group=group, person=d['person'])
return group

def update(self, instance, validated_data):
person_data = validated_data.pop('memberships')
for item in validated_data:
if Group._meta.get_field(item):
setattr(instance, item, validated_data[item])
Membership.objects.filter(group=instance).delete()
for person in person_data:
d=dict(person)
Membership.objects.create(group=instance, person=d['person'])
instance.save()
return instance

class Meta:
model = Group

class GroupCreateModelViewSet(ModelViewSet):
serializer_class = GroupCreateSerializer
queryset = Group.objects.all()

因此您可以使用相关人员创建一个新组:

 { 
"name" : "Group 1",
"memberships" : [
{ "person" : 1 },
{ "person" : 2 }
]
}

关于python - DRF 3 - 使用表创建多对多更新/创建序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28706072/

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