【发布时间】:2020-07-31 06:16:45
【问题描述】:
我在 Django 中使用 PostgreSQL 有以下 Schema。
Class Person (models.Model):
name = models.CharField(max_length=255)
email= models.CharField(max_legth = 255)
created_at = models.DateTimeField()
Class PersonTask(models.Model):
person = models.ForeignKey(Person)
title = models.TextField()
created_at = models.DateTimeField()
Class PersonHistory(models.Model):
person = models.ForeignKey(Person)
note = models.TextField()
created_at = models.DateTimeField()
现在我需要查询数据库,比如最新PersonTask__title 为max_task 和最新PersonHistory__note 为max_note 的 Person 的所有值
例如:
<Queryset: [
{name: "abc" ,email:"abc@gmail.com",created_at :"2019-01-02", max_task:"This is my latest tasktitle" , max_note: "This is my latest history note"},
{name: "abcd" ,email:"abcd@gmail.com",created_at :"2019-03-02", max_task:"This is my latest tasktitle for abcd" , max_note: "This is my latest history note for abcd"}
]>
但是,我最多可以得到最新任务和最新历史的 id
Person.objects.filter(customer_id= 1).\
annotate( max_task = Max('persontask')).\
annotate(max_note = Max('personhistory')).\
order_by('-id')
或使用以下查询的随机任务或注释文本
Person.objects.filter(customer_id= 1).\
annotate( max_task = Max('persontask__title')).\
annotate(max_note = Max('personhistory__note')).\
order_by('-id')
如何解决这个问题??
【问题讨论】:
标签: django django-orm django-annotate