In Django, QuerySet.Values() method helps us get specific fields from the database as dictionaries, making our queries simpler. This can be incredibly useful when we only need certain pieces of information from our model without the overhead of loading the full object.
What is QuerySet.values()?
The values() method returns a QuerySet that yields dictionaries, where each dictionary represents a row of the database and the keys correspond to the fields you specify. If no fields are specified, values() returns all fields of the model in the form of a dictionary.
Let's say we have the following model:
from django.db import models
class Cricketer(models.Model):
title = models.CharField(max_length=255)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
Retrieve All fields
To retrieve all fields of a Cricketer using values():
cricketers = Cricketer.objects.values()
This will return a QuerySet of dictionaries with all fields:
<QuerySet [
{'id': 1, 'title': 'godfather of cricket', 'name': 'Dhoni', },
{'id': 2, 'title': 'king of cricket', 'cricketername': 'Kohli'},
{'id': 3, 'title': 'god of cricket', 'cricketername': 'Sachin'}
]>
Retrieve Specific Fields:
Let's see how can we fetch only 'title' of all cricketers
cricketers = Cricketer.objects.values('title')
Output:
<Queryset[
{'id':1, 'title': 'godfather of cricket'},
{'id': 2, 'title': 'king of cricket'},
{'id': 3, 'title': 'god of cricket'}
]>
Using values() for a Single Object
When working with a single object, we might need to retrieve just a specific set of fields instead of the whole model. The values() method works seamlessly for retrieving data from a single object when combined with methods like filter().
Example 1: Using filter() with values()
cricketer = Cricketer.objects.filter(id=1).values('title', 'cricketername').first()
Output:
{'id': 1, 'title': 'God father of cricket', 'cricketername': 'Dhoni'}Here, filter() is used to retrieve the Cricketer object with id=1, and values() ensures that only the title and author fields are fetched from the database. The first() method is used to get the first (and only) result as a dictionary.
Example 2: Using get() with values()
The values() method is a attribute of a queryset not a instance of Model objects. So, we cannot use values() method with a single object.
We can access the fields directly without using values():
cricketer = Cricketer.objects.get(id=1)
cricketer_dict = {
'title': cricketer.title,
'name': cricketer.name
}
print(cricketer_dict)
Output:
{'title': 'God father of cricket', 'cricketername': 'Dhoni'}
Conclusion
Django’s QuerySet.values() is an efficient way to retrieve specific fields from the database in the form of dictionaries, particularly useful when we don't need full model instances. For single objects, values() can help improve performance and reduce the memory footprint of your queries.
Key takeaways:
- Use
values()when we need a dictionary representation of specific fields. - Combine
filter()withvalues()andfirst()to fetch specific fields for a single object. - Avoid
get()withvalues()as it returns a model instance. - Use
values()judiciously to optimize performance but remember it comes at the cost of losing access to model instance methods.
By mastering the use of values(), we can create more efficient queries and improve the performance of our Django applications, particularly when working with large datasets or optimizing API responses.