Search code examples
pythondjangomindjango-aggregation

Get minimum value field name using aggregation in django


I have a model with some fields like below

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

So i want to get the field name that has the lowest price value, so in order to get the lowest price value, we can do like below using Aggregations

from django.db.models import Avg, Max, Min

choclates = Choclate.objects.all()
lowest_price = choclates.aggregate(Min('price'))

So finally how to get the field name, that related to lowest price value in django ?


Solution

  • You can try below code to get 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 field name having price = 10 which is lowest value.

    Documentation Link