gpt4 book ai didi

Django-rest-framework 创建具有多对多关系的对象

转载 作者:行者123 更新时间:2023-12-05 00:15:43 25 4
gpt4 key购买 nike

我需要创建对象“标签”,其中多对多关系附加到对象“任务”。我有这段代码,但不明白为什么它不起作用。我看到错误无法将关键字“任务”解析为字段。选项有:id、名称、标签、
附言
我靠这个帖子manyToMany with django rest framework

。楷模

class Tag(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return "{}".format(self.name)

class Task(models.Model):
name = models.CharField(max_length=200, blank=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return "{}".format(self.name)

.views
class TagCreateView(generics.ListCreateAPIView):
serializer_class = TagSerializer

def get_queryset(self):
queryset = Tag.objects.all()
task_id = self.kwargs.get('task_id', None)
if task_id is not None:
queryset = queryset.filter(task=task_id)
return queryset
def perform_create(self, serializer):
task_id = self.kwargs.get('task_id', None)
try:
tasks = Task.objects.get(task__id__exact=task_id)
except Task.DoesNotExist:
raise NotFound()
serializer.save(tag=tasks)

.serelizers
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'name','')

class TaskSerializer(serializers.ModelSerializer):
tag = TagSerializer(many=True, read_only=True)
class Meta:
model = Task
fields = ('id', 'name', 'tags')
read_only_fields = ('tags')

.urls
urlpatterns = {
url(r'^todolists/(?P<task_id>[0-9]+)/tags', TagCreateView.as_view(), name="tags")}

最佳答案

您需要在序列化程序中处理嵌套序列化程序的创建 create方法;

如下所示:http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations

关于Django-rest-framework 创建具有多对多关系的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853588/

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