过滤器的Django查询设置相关领域的最早实例的价值

问题描述 投票:1回答:1

鉴于以下车型

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',)

是否有可能使用Django的ORM工具(没有太多的原始SQL编写和查询后在内存中处理),以获得Things的查询集为其最新的时间戳的值为bar

换句话说,我想重新写了下面的代码,并实现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)
python django
1个回答
0
投票

纵观Subquery文档,ORM cookbook,你的病情,如果我想你可能尝试类似如下:

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")

虽然我不是现在能够验证这一权利。总之,非常有趣的问题,我不知道那些到现在为止。

© www.soinside.com 2019 - 2024. All rights reserved.