Django 查询集获取每个唯一属性值的最新值
class SwallowMigration(models.Model):
swallow = models.ForeignKey(Swallow)
date = models.DateTimeField(auto_now_add=True)
coconuts_carried = models.IntegerField()
如何获取每只燕子的最新迁徙信息?
当然 .latest() 只给我最新的条目。有没有办法(也许使用 Max 聚合?)来获取另一个字段中某个值的每个实例的最新信息?
class SwallowMigration(models.Model):
swallow = models.ForeignKey(Swallow)
date = models.DateTimeField(auto_now_add=True)
coconuts_carried = models.IntegerField()
How can I get the latest migration for each swallow?
Of course .latest() only gives me the very most recent entry. Is there a way (maybe using Aggregation with Max?) to get the latest for each instance of some value in another field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果仅拥有 Swallow 实例并且仅最近迁移的日期就足够了,那么以下内容应该可以为您做到这一点:
结果查询集中的每个 Swallow 实例都将具有一个“latest_migration”属性,该属性将是相关对象的最大日期时间。
如果您确实需要 SwallowMigration 实例,则将花费 N+1 次查询,其中 N 是 Swallow 实例的数量。尽管您将拥有 SwallowMigration 对象,每个对象上都有一个预取的 Swallow 实例,而不是相反,但类似下面的内容可以为您做到这一点。通过将 SwallowMigration 实例设置为 Swallow 实例的属性,处理该列表并反转它们并不困难。
可能(可能是)有一种方法可以在单个查询中返回您想要的所有数据,但它必须是原始 SQL,并且您必须按原样使用其中的数据或从中构造模型实例。
如果要频繁执行此代码,则可能值得将 Swallow 上的外键添加到最新的 SwallowMigration,以便您可以使用 select_lated() 在单个查询中轻松检索它们。您只需确保在添加新的 SwallowMigration 实例时保持外键更新即可。
If just having the Swallow instance and only the date of the most recent migration is enough, the following should do that for you:
Each Swallow instance from the resulting queryset will have a "latest_migration" attribute which would be the maximum datetime from the related objects.
If you do need the SwallowMigration instance, it is going to cost you N+1 queries, where N is the number of Swallow instances. Something like the following would do that for you, though you would have SwallowMigration objects with a prefetched Swallow instance on each instead of the other way around. It wouldn't be difficult to process the list and reverse them, setting the SwallowMigration instance as an attribute of the Swallow instance.
There may be (probably is) a way to return all of the data you want in a single query, but it would have to be raw SQL and you'd have to either use the data from that as is or construct model instances from it.
If this code is going to be executed frequently, it might be worth it to add a foreign key on Swallow to the latest SwallowMigration so that you can easily retrieve them in a single query using select_related(). You'd just have to make sure to keep that foreign key updated as new SwallowMigration instances are added.
嗯,我认为你可以像这样使用 Max:
但我不确定它对你有什么好处,因为你必须通过 id 获取所有迁移,然后将它们附加到 Swallow 上。
Hm i think you can use Max like this:
But i'm not sure what good would it make for you, since you'll have to fetch all migrations by id and then attach them to Swallow anyway.