简体   繁体   English

根据相关字段最早实例的值过滤Django查询集

[英]Filter Django query set on value of earliest instance of related field

Given the following models 给定以下模型

class Thing(models.Model):
    ...

class Status(models.Model):
   thing = models.ForeignKey(Thing, ...)
   value = models.CharField(choices=(('foo', 'foo'), ('bar', 'bar')), ...)
   timestamp = models.DateTimeField(auto_now_add=True)

   class Meta:
      ordering = ('timestamp',)

Is it possible by using the Django ORM tools (without much raw SQL writing and post-query in-memory processing) to get the queryset of Thing s for which the latest timestamp has the value bar ? 是否可以使用Django ORM工具(无需进行大量原始SQL编写和查询后的内存中处理)来获取Thing的查询集,其最新时间戳的值为bar

In other words, I'd like to re-write the following code and achieve the same value for queryset : 换句话说,我想重新编写以下代码,并为queryset实现相同的值:

thing_ids = []
for thing in Thing.objects.all():
    status = thing.status_set.last()
    if status is not None and status.value == 'bar':
        thing_ids.append(thing.id)

queryset = Thing.objects.filter(id__in=thing_ids)

Looking at Subquery documentation, ORM cookbook , and your if condition I think you might try something like following: 查看子查询文档, ORM cookbook和if条件,我认为您可以尝试如下操作:

latest_status = Status.objects.filter(thing_id=OuterRef("pk")).order_by("-timestamp")
queryset = Thing.objects.annotate(
    lastest_status=Subquery(latest_status.values("value")[:1])
).filter(latest_status="bar")

Although I am not able to verify this right now. 尽管我现在无法验证。 Anyway, very interesting question, I wasn't aware of those until now. 无论如何,一个非常有趣的问题,直到现在我才意识到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM