Django rest框架多对一关系



我想显示与任务相关的附件列表。如何传递任务的pk(uuid(?到目前为止,我尝试了这个:

型号.py

class Task(Timestamp):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False)
title = models.CharField(max_length=50)
description = models.TextField()
def __str__(self):
return self.title
class Attachment(Timestamp):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False)
task = models.ForeignKey(Task, on_delete=models.CASCADE)
attachment = models.FileField(upload_to='tasks-attachments/%Y-%m-%d/')
def __str__(self):
return self.task.title + " attachment"

serializers.py

class AttachmentSerializer(serializers.ModelSerializer):

class Meta:
model = Attachment
fields = [
'id',
'task',
'created_at',
'updated_at',
'attachment'
]

views.py

class AttachmentsView(generics.ListCreateAPIView):
serializer_class = AttachmentSerializer
def get_queryset(self):
return Attachment.objects.filter(task=task__id)

urls.py

urlpatterns = [
path('tasks/', TasksView.as_view()),
path('tasks/<uuid:pk>', TaskView.as_view()),
path('tasks/<uuid:pk>/attachments/', AttachmentsView.as_view())
]

首先将related_name添加到Attachment模型上的任务字段中,related_name已经存在,默认命名由Django完成,但最好添加您的。

related_name是反向关系的名称,因此您可以从引用的对象中获取相关对象,因此它应该是:

task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='attachments')

这就是为什么它具有值attachments,因为我们稍后将从task对象中使用它,所以正确的命名将消除任何混淆。

最后,如果要使用ModelSerializer,请创建一个任务序列化程序,并将attachments添加到它的fields中,以便它将相关对象与其他任务字段一起序列化。

例如:

class TaskSerializer(serializers.ModelSerializer):
attachments = AttachmentSerializer(read_only=True, many=True)
class Meta:
model = Task
fields = ['id', 'title', 'attachments']

相关内容

  • 没有找到相关文章

最新更新