get field value in django queryset

How to Get Field Value in Django Queryset

Django is a popular web framework to build python-based websites and web applications. It allows you to build querysets to extract data from Django Objects. But the default result of queryset is a list of objects. Sometimes you may need to get field value in Django queryset. Here are the steps to get field value in Django queryset.


How to Get Field Value in Django Queryset

Here are the steps to get field value in Django queryset. Let us say you have an object User(id, name, age, gender). Let us say you want to extract value of name and age fields in your User object.

Here is the python code to do it. Replace <your queryset> with your queryset.

user_qs = <your queryset>
for user in user_qs:
    print(user['name'],user['age'])

In the above code, the query set returns a list of objects. We loop through the objects and access the required field values, just as we get dictionary values using keys.

If you want to get the get field value of first object, you can use the following shortcut. You can change 0 to the index of object that you want to access.

name = User.objects.all()[0]['name']
age = User.objects.all()[0]['age']

In this short article, we have learnt how to get field value in Django.

Also read:

How to Convert Markdown to HTML in Python
How to Configure DNS Server in RHEL/CentOS
Python Delete Dictionary Key Using Iteration
Python Remove Item from List During Iteration
How to Rename File Using Python

Leave a Reply

Your email address will not be published. Required fields are marked *