如何在 Django RestFramework API 中将 manytomanyfield 作为对象返回
Posted
技术标签:
【中文标题】如何在 Django RestFramework API 中将 manytomanyfield 作为对象返回【英文标题】:How to return manytomanyfield as object in Django RestFramework API 【发布时间】:2022-01-21 12:40:51 【问题描述】:我尝试使用 Django RestFramework 创建一个 API,因此我创建了 2 个模型 Note 和 Task,并在 Note 模型中有一个 ManyToManyField,因此我可以将许多任务放在一个 Note 但我创建的 API 不返回完整的对象功能但是只是身份证。这是我的代码:
class NoteAPI(ListAPIView):
serializer_class = NoteSerializer
queryset = Note.objects.all()
这是我的模型:
class Task(models.Model):
task = models.CharField(max_length=255, null=False, blank=False)
detail = models.CharField(max_length=255, null=True, blank=True)
completed = models.BooleanField(default=False)
priority = models.IntegerField(default=0)
def __str__(self):
return self.task
class Note(models.Model):
title = models.CharField(max_length=255, null=False, blank=False)
priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES, default="B")
detail = models.CharField(max_length=255, null=True, blank=True)
completed = models.BooleanField(default=False)
task = models.ManyToManyField(Task, related_name="note_task", blank=True)
process = models.IntegerField( default=0, validators=[max_int_value])
def __str__(self) -> str:
return self.title + " is "+ str(self.process) + "% completed"
我希望输出罐看起来像:
[
"id": 2,
"title": "Sleep",
"priority": "F",
"detail": "Don't do it, stay awake and do your job",
"completed": false,
"process": 0,
"task": [
"id": 1,
"task": "Go to bed",
"completed": false
,
"id": 2,
"task": "Start counting",
"completed": false
]
]
但实际上是这样的
[
"id": 2,
"title": "Sleep",
"priority": "F",
"detail": "Don't do it, stay awake and do your job",
"completed": false,
"process": 0,
"task": [
1,
2
]
]
那么我能做些什么来得到这样的输出呢?
【问题讨论】:
【参考方案1】:你需要告诉NoteSerializer
如何序列化Task
objectcs。
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ("id", "task", "completed")
class NoteSerializer(models.Model):
task = TaskSerializer(many=True)
您可能还希望预取任务以将数据库查询的数量保持在最低限度。
class NoteAPI(ListAPIView):
serializer_class = NoteSerializer
queryset = Note.objects.prefetch_related("task").all()
【讨论】:
哦,非常感谢。我花了整个下午才找到这个 ***.com/help/someone-answers 对不起,我认为我的声望必须达到 15 才能投票。以上是关于如何在 Django RestFramework API 中将 manytomanyfield 作为对象返回的主要内容,如果未能解决你的问题,请参考以下文章