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 create enum in java

What is enum in Java? An enum is a special "data type" that used to create our own datatype like classes and It represents a group of constants (a variable that does not change). The enum is short for "enumerations", which means "specifically listed" and the Enum data also known as Enumerated Data Type. # Defining Java enum Instead of C/C++, in java programming language enum types are more powerful. Here, we can define an enum both inside and enum outside the class but not inside a Method "Rules" to defing enum in Java: To create an enum in Java, use the enum keyword (instead of class or interface) , and separate the constants with a comma (,) . The enum can be defined within or outside the class because it is similar to a class. The semicolon (;) at the end of the enum constants are optional Because enum are constants, the names of an enum type's fields are in uppercase letters. ...