Aggregation and extra values with Django

家住魔仙堡 提交于 2019-12-24 09:18:04

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/3181854/aggregation-and-extra-values-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!