获取每个组的最新条目
我正在尝试在 django 4.0 中构建一个简单的存储示例,其中的内容被插入到如下定义的存储表中:
class material_storage(models.Model):
storage_id = models.AutoField(primary_key=True)
material = models.ForeignKey(itemtype, on_delete=models.PROTECT)
amount = models.IntegerField(null=True)
price = models.FloatField(null=True)
timestamp = models.DateTimeField(default=timezone.now)
要检索此表中每种材料的最新条目,我需要在 SQL 中看起来像这样的内容:
SELECT material_id, amount, price, MAX(timestamp)
FROM assetmanager_material_storage
GROUP BY material_id
因为我是新手Django,我还没有设法重新创建这个查询。我发现一些线程建议解决方案,例如:
material_storage.objects.values('material').annotate(latest_record=Max('timestamp'))
但这在我的情况下不起作用,而是抛出错误“名称'Max'未定义”。另一种方法是这样的:
material_storage.objects.all().latest('timestamp')
但这只会返回整个表中的最新对象,而且我现在无法弄清楚如何在每个材料而不是所有记录上应用“最新”。所以我现在有点卡住了。如果有人能告诉我我缺少什么,我将不胜感激。
提前谢谢。
I am trying to build a simple storage example in django 4.0 where stuff is inserted to a storage table defined like this:
class material_storage(models.Model):
storage_id = models.AutoField(primary_key=True)
material = models.ForeignKey(itemtype, on_delete=models.PROTECT)
amount = models.IntegerField(null=True)
price = models.FloatField(null=True)
timestamp = models.DateTimeField(default=timezone.now)
To retrieve the latest entry for every material within this table I need something looking like this in SQL:
SELECT material_id, amount, price, MAX(timestamp)
FROM assetmanager_material_storage
GROUP BY material_id
Since I'm new to Django, I haven't managed to recreate this query yet. I found some threads suggesting solutions like:
material_storage.objects.values('material').annotate(latest_record=Max('timestamp'))
but that's not working in my case, instead throwing an error "name 'Max' not defined". The other approach would be to go like this:
material_storage.objects.all().latest('timestamp')
but this would only return the latest object in the whole table and I couldn't figure out for now how to apply "latest" on every material instead of all records. So I am kinda stuck now. If somebody could tell me what I'm missing, I would be grateful.
thx in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论