我一直在玩 Django ORM 中的新聚合功能,我认为有一类问题应该是可能的,但我似乎无法让它工作。此处描述了我尝试生成的查询类型。
所以,假设我有以下模型 -
class ContactGroup(models.Model):
.... whatever ....
class Contact(models.Model):
group = models.ForeignKey(ContactGroup)
name = models.CharField(max_length=20)
email = models.EmailField()
...
class Record(models.Model):
contact = models.ForeignKey(Contact)
group = models.ForeignKey(ContactGroup)
record_date = models.DateTimeField(default=datetime.datetime.now)
... name, email, and other fields that are in Contact ...
因此,每次创建或修改联系人时,都会创建一个新记录,以保存当时出现在联系人中的信息以及时间戳。现在,我想要一个查询,例如,返回与 ContactGroup 关联的每个联系人的最新记录实例。在伪代码中:
group = ContactGroup.objects.get(...)
records_i_want = group.record_set.most_recent_record_for_every_contact()
一旦我弄清楚了这一点,我只想能够在查询集上抛出一个filter(record_date__lt=some_date)
,并获取它存在于some_date
.
有人有什么想法吗?
编辑:看来我并没有真正让自己清楚。使用这样的模型,我想要一种使用纯 django ORM(没有额外())执行以下操作的方法:
ContactGroup.record_set.extra(where=["history_date = (select max(history_date) from app_record r where r.id=app_record.id and r.history_date <= '2009-07-18')"])
将子查询放在 where 子句中只是解决此问题的一种策略,我上面给出的第一个链接很好地涵盖了其他策略。我知道如果不使用 extra(),where-clause 子选择是不可能的,但我认为新的聚合功能可能使其他方法之一成为可能。