class Pages(models.Model):
pagename = models.CharField(
max_length=150,
unique=True,
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
pagenumber = models.IntegerField(default=1)
class Paras(models.Model):
paraname = models.CharField(
max_length=150,
unique=True,
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
paranumber = models.IntegerField(default=1)
pagenumberID = models.ForeignKey(Pages, related_name='page')
Post API:/ para 发布数据:
{
pagename:Page1,
pagenumber:1,
paras:[
{
paraname:para1,
paranumber:1
},
{
paraname:para2,
paranumber:2
},
{
paraname:para3,
paranumber:3
}
]
}
post API的目的是在创建页面后在一个批量调用中创建多个参数。
我有两个Serialiazer:
但是我怀疑如何一次性处理完整的请求。将业务逻辑保留在视图中,即先调用CreatePageSerializer然后再调用CreateParaSerializer似乎不正确。
我正在考虑创建另一个序列化器:CreateBulkSerializer(BaseSerialzer),该序列化器随后将调用CreatePageSerializer和CreateParaSerializer。但是问题是:
或者我在这里还缺少其他方法吗?
答案 0 :(得分:2)
将 create()方法重写为,
class ParasSerializer(serializers.ModelSerializer):
class Meta:
model = Paras
fields = ('paraname', 'paranumber')
class PagesSerializer(serializers.ModelSerializer):
paras = ParasSerializer(write_only=True, many=True)
class Meta:
model = Pages
fields = '__all__'
def create(self, validated_data):
paras = validated_data.pop('paras')
page = Pages.objects.create(**validated_data)
for para in paras:
Paras.objects.create(**para, pagenumberID=page)
return page
我想使用 viewset
类进行查看,
from rest_framework import viewsets
class PagesAPI(viewsets.ModelViewSet):
queryset = Pages.objects.all()
serializer_class = PagesSerializer
使用下面的JSON进行批量创建,
{
"pagename":"Page1",
"pagenumber":1,
"paras":[
{
"paraname":"para1",
"paranumber":1
},
{
"paraname":"para2",
"paranumber":2
},
{
"paraname":"para3",
"paranumber":3
}
]
}
参考
1. write_only
2. DRF Nested relationship
3. Writable Nested Serializers