# In this section you will learn, How to fetch single OR column data from database in Django ORM.
Select a single field from database with django QuerySet.
In django with the help of ' values_list() 'method you can fetch single or more column datafrom database.
Your "posts" models is like this :
➤ Example : models.py;
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
# values_list()
It is similar to values() except that instead of returning dictionaries, 'values_list' returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call so the first item is the first field, etc.
For example:
# 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 either return true/false.
# If flat=True, this will mean 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,), ...]
# Without flat=True
Posts.objects.values_list('id', flat=True)
______________ OUTPUT ______________
[1, 2, 3, ...]
# values_list raise an error to pass in flat when there is more than one field. For example:
Posts.objects.values_list('id', 'title', flat=True)
Output:
Important point's of values_list() method:
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.
values_list method returns a ValuesListQuerySet and this class behaves like a list. Most of the time this is enough, but if you require an actual Python list object, you can simply call list() on it, which will evaluate the queryset.
A common requirement is to get the specific field value of a certain model instance, to get this, use value_list() and then call the get() method.
# Code
Posts.objects.values_list('title', flat=True).get(pk=1)
# Output
'First entry'
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.