'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 1:[1]

If you pass the Min as positional argument, then the field's name is price__min. Otherwise, if you pass it as 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

Solution 2:[2]

For Min and Max you may order your values (QuerySet result) and grab the first() and last():

chocolate_list = Chocolate.objects.values_list('name', 'price')
min = chocolate_list.order_by('price').first()
max = chocolate_list.order_by('price').last()

PS: Remove the filter() if you are not assigning nothing. With values_list() you are implicitly instancing the QuerySet class

Solution 3:[3]

Usage of what @Maciej Gol said:

from django.db.models import Min    

lowest_price = Chocolate.objects.values('price').aggregate(Min('price'))['price__min']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maciej Gol
Solution 2
Solution 3 Yotam Sofer