使用 Django 进行聚合和附加值
我有一个如下所示的模型:
class MyModel(models.Model)
value = models.DecimalField()
date = models.DatetimeField()
我正在执行此请求:
MyModel.objects.aggregate(Min("value"))
并且我得到了预期的结果:
{"mymodel__min": the_actual_minimum_value}
但是,我无法找到一种方法来同时获取最小值和关联的日期(最小值出现的日期)。
Django ORM 是否允许这样做,还是我必须使用原始 SQL ?
I have a model which looks like this:
class MyModel(models.Model)
value = models.DecimalField()
date = models.DatetimeField()
I'm doing this request:
MyModel.objects.aggregate(Min("value"))
and I'm getting the expected result:
{"mymodel__min": the_actual_minimum_value}
However, I can't figure out a way to get at the same time the minimum value AND the associated date (the date at which the minimum value occured).
Does the Django ORM allow this, or do I have to use raw SQL ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要做的是对查询进行注释,以便您返回通常的结果,同时还将一些数据添加到结果中。所以:
将返回正常结果,并将
mymodel__min
作为附加值回复您的评论,我认为这就是您正在寻找的?这将返回日期及其相应的最小值。
编辑:在进一步回复您的评论时,您想要最低值的条目,但也希望结果中包含附加日期字段,您可以这样做:
这将通过对结果进行排序来获得您要求的结果字典,然后只需采用第一个索引,该索引始终是最低值。
请参阅 更多
What you want to do is annotate the query, so that you get back your usual results but also have some data added to the result. So:
Will return the normal result with
mymodel__min
as an additional valueIn reply to your comment, I think this is what you are looking for? This will return the dates with their corresponding Min values.
Edit: In further reply to your comment in that you want the lowest valued entry but also want the additional date field within your result, you could do something like so:
This will get the resulting dict you are asking for by ordering the results and then simply taking the first index which will always be the lowest value.
See more