How to fetch single column from database in Django | Django values_list querysets
How to Fetch Single or Column Data from Database in Django ORM
In Django, with the help of the values_list() method, you can fetch single or multiple column data from your database efficiently.
Introduction
The values_list() method is similar to values(), except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call.
Example Model
Your Posts model is like this:
class Posts(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=155)
class Meta:
verbose_name_plural = "Posts"
def __str__(self):
return self.title
Basic Usage
# Fetch single column data
Posts.objects.values_list('id',)
# Fetch more than one column data
Posts.objects.values_list('id', 'title',)
# You can also fetch in order_by
Posts.objects.values_list('id', 'title',).order_by('?')
Note: You can also pass in a flat parameter if you only pass in a single field. It will return true/false values.
Understanding flat=True
If flat=True, the returned results are single values, rather than one-tuples. Let's look at an example to make the difference clear:
# Without flat=True
Posts.objects.values_list('id')
# Output: [(1,), (2,), (3,), ...]
# With flat=True
Posts.objects.values_list('id', flat=True)
# Output: [1, 2, 3, ...]
Important Limitation
values_list raises an error if you try to pass in flat=True when there is more than one field.
# This will raise an error
Posts.objects.values_list('id', 'title', flat=True)
Important Points
- All Fields: If you don't pass any values to
values_list(), it will return all the fields in the model, in the order they were declared. - QuerySet Behavior:
values_listmethod returns aValuesListQuerySetthat behaves like a list. If you require an actual Python list object, you can calllist()on it. - Getting Specific Values: A common requirement is to get the specific field value of a certain model instance. Use
values_list()and then call theget()method.
Example of getting a specific value:
# Code
Posts.objects.values_list('title', flat=True).get(pk=1)
# Output
'First entry'
values_list() vs values()
| Feature | values_list() | values() |
|---|---|---|
| Return Type | Tuples | Dictionaries |
| Memory Usage | Lower (more efficient) | Higher |
| Best For | Getting specific field values | Getting labeled data |
Summary
values_list() is a powerful and efficient method for fetching specific columns from your database. Use it when you need specific field values, especially with flat=True for single fields to get clean, flat lists of values.
Remember: flat=True only works with single fields, and calling values_list() without arguments returns all fields in declaration order.
Recommended Posts
Join the discussion
Comments
Best Website Development Company in India
Graphics Designing Canada
At IBX, the products go wild when you explore the non limiting website. We are offering the best website malware protection application at affordable prices. So visit to explore!
Best Web Hosting Services
I wish you to keep writing similar blogs in the future.
Apart from this, if you ever need Best Software Development Company then you can get all the information on this website.