gpt4 book ai didi

django 在 post/put 中休息嵌套关系

转载 作者:行者123 更新时间:2023-12-04 15:35:00 24 4
gpt4 key购买 nike

我是 Django rest api 开发的新手。我有两个模型,一个是类别,另一个是子类别。
这是我的模型

class Category(models.Model):
title = models.Charfield()
brief = models.TextField()
subcategories = model.ManyToManyField('Subcategory', blank=True)

我的序列化器类
class CategorySerializer(serializers.ModelSerializer):
title= serializer.Charfield()
subcategories = Relatedfield(many=True)

现在看来
def post(self, request, format = None):
data=request.DATA
serialize= CategorySerializer(data=request.DATA)
if serializer.valid():
serializer.save()

如何保存嵌套数据,如 {'title':"test",'subscategories':[{'description':'bla bla bla'},{'description':'test test'}]}在post方法中。

我已经在文档中阅读了这个

Note: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the RelatedField subclasses.



请让我建议在 django rest 中进行嵌套关系发布/放入的正确方法或解决方案。

最佳答案

您是否尝试过创建 SubCategorySerializer并将其添加为 CategorySerializer 上的字段?

class SubcategorySerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory

class CategorySerializer(serializers.ModelSerializer):
subcategories = SubcategorySerializer(many=True)

文档: http://django-rest-framework.org/api-guide/relations.html#nested-relationships

关于django 在 post/put 中休息嵌套关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17146412/

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