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 ?
This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.
Unlike aggregate() , annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet ; this QuerySet can be modified using any other QuerySet operation, including filter() , order_by() , or even additional calls to annotate() .
values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With