Get minimum field name using aggregation in django

I have a model with some fields as shown below

class Choclate(models.Model): name = models.CharField(max_length=256) price = models.IntegerField() 

So, I want to get the name of the field with the lowest price value, so to get the lowest price value, we can do, as shown below, using Aggregations

 from django.db.models import Avg, Max, Min choclates = Choclate.objects.all() lowest_price = choclates.aggregate(Min('price')) 

So how to get the field name associated with the lowest price in django?

+8
python django min django-aggregation
source share
2 answers

You can try under the code to get the exact thing you want.

 >>> from django.db.models import Min >>> Choclate.objects.filter().values_list('name').annotate(Min('price')).order_by('price')[0] (u'First1', 10) >>> 

First1 is the name of the field, having a price = 10, which is the lowest value.

+8
source share

If you pass Min as a positional argument, then the field name is price__min . Otherwise, if you pass it as a keyword argument, i.e. aggregate(my_min=Min('price')) , then it will be available with the same name as the argument, in this case my_min . Docs

+1
source share

All Articles