Django的聚合和额外价值 [英] Aggregation and extra values with Django

查看:70
本文介绍了Django的聚合和额外价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的模型:

I have a model which looks like this:

class MyModel(models.Model)
    value = models.DecimalField()
    date = models.DatetimeField()

我正在执行此请求:

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

Django ORM允许这样做吗,还是我必须使用原始SQL?

Does the Django ORM allow this, or do I have to use raw SQL ?

推荐答案

您想要做的是对查询进行注释,这样您不仅可以获取通常的结果,还可以向结果中添加一些数据.所以:

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

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

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

要进一步答复您的评论,即您希望获得价值最低的条目,但又希望结果中包含其他日期字段,可以执行以下操作:

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

这篇关于Django的聚合和额外价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆