我想在DRF 3中創建一個參考應用程序來演示可以創建/更新模型的嵌套序列化程序。在嘗試創建嵌套模型時,**之後具有「* create()參數炸彈的示例代碼必須是映射,而不是列表*」。我也不清楚如何處理.update(),因爲在某些情況下,我只是想建立更多的關係(人員)。DRF 3 - 創建多對多更新/創建序列化雖然表
樣品型號:
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)
而串行和viewsets:
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"
}
的手指越過了,我可以像這樣得到類似於這個用例的工作,將會回報。 – seanmus 2017-05-12 21:15:05