Skip to main content

How to fetch single column from database in Django | Django values_list querysets

# In this section you will learn, How to fetch single OR column data from database in Django ORM.

django values_list querysets | How to fetch single column from database in Django | How to select a single field from database with django QuerySet

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:
  1. # fetch single column data

  2. Posts.objects.values_list('id',)

  3.  

  4. # fetch more than one column data

  5. Posts.objects.values_list('id', 'title',)

  6.  

  7. # You can also fetch in order_by

  8. 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:

  1. # Without flat=True

  2. Posts.objects.values_list('id')

  3.  

  4. ______________ OUTPUT ______________

  5. [(1,), (2,), (3,), ...]

  6.  

  7. # Without flat=True

  8. Posts.objects.values_list('id', flat=True)

  9.  

  10. ______________ OUTPUT ______________

  11. [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:
Django values_list querysets

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'

Recommended Posts:

Comments

Deepanshu said…
Hi! I really like your content, Your post is really informative.
Best Website Development Company in India
Bhaskar Sharma said…
ITSWS Technologies is a proven IT solutions provider. We have provided highly customized, affordable web-based solutions to customers around the world since 2013.

6sensetech said…
This is one the many useful blogs I have came across, thanks for the upload.
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
Insbytech said…
Your blog is really great, I really appreciate the efforts that you are doing for us.
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.

Popular Posts

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return...

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve...

How to remove ? m=1 or ?m=0 from blogger post URL

# Remove m=1 From URL of Blogger post A Common search term that every blogger search is How to ?m=1 or ?m=0 from blogger Post URL. We all know that "simplicity is beauty" and you want to clean permalink. So, in this article, I will guide you on how to remove ?m=1 from the blogger URL, and make a simple professional URL. Follow the few steps below and removed ?m=1 from the URL of your blogger post. Step 1 : First, you login into your blogger's dashboard and then select your blog. Step 2 : Click on the Theme option. Step 3 : Click on the customise Step 4 : Click on Edit HTML option. Step 5 : Press (CTRL + F) from the keyboard and type "/head" and then search. ( If you are not understanding, see the below photo ) Step 6 : Now paste the below code just above the </head> tag. let's see code :   ➤ Code : mycode.js; Copy code ...