使用 Django 进行聚合和附加值

发布于 2024-09-08 17:36:10 字数 405 浏览 2 评论 0原文

我有一个如下所示的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪荡不羁 2024-09-15 17:36:10

您想要做的是对查询进行注释,以便您返回通常的结果,同时还将一些数据添加到结果中。所以:

MyModel.objects.annotate(Min("value"))

将返回正常结果,并将 mymodel__min 作为附加值

回复您的评论,我认为这就是您正在寻找的?这将返回日期及其相应的最小值。

MyModel.objects.values('date').annotate(Min("value"))

编辑:在进一步回复您的评论时,您想要最低值的条目,但也希望结果中包含附加日期字段,您可以这样做:

MyModel.objects.values('date').annotate(min_value=Min('value')).order_by('min_value')[0] 

这将通过对结果进行排序来获得您要求的结果字典,然后只需采用第一个索引,该索引始终是最低值。
请参阅 更多

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:

MyModel.objects.annotate(Min("value"))

Will return the normal result with mymodel__min as an additional value

In reply to your comment, I think this is what you are looking for? This will return the dates with their corresponding Min values.

MyModel.objects.values('date').annotate(Min("value"))

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:

MyModel.objects.values('date').annotate(min_value=Min('value')).order_by('min_value')[0] 

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文