Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Django QuerySet.values() for Single Object
Next article icon

Django QuerySet.values() for Single Object

Last Updated : 18 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, QuerySet.Values() method helps us get specific fields from the database as dictionaries, making our queries simpler. This can be incredibly useful when we only need certain pieces of information from our model without the overhead of loading the full object.

What is QuerySet.values()?

The values() method returns a QuerySet that yields dictionaries, where each dictionary represents a row of the database and the keys correspond to the fields you specify. If no fields are specified, values() returns all fields of the model in the form of a dictionary.

Let's say we have the following model:

Python
from django.db import models  class Cricketer(models.Model):     title = models.CharField(max_length=255)     name = models.CharField(max_length=255)          def __str__(self):       	return self.name 

Retrieve All fields

To retrieve all fields of a Cricketer using values():

Python
cricketers = Cricketer.objects.values() 

This will return a QuerySet of dictionaries with all fields:

<QuerySet [
{'id': 1, 'title': 'godfather of cricket', 'name': 'Dhoni', },
{'id': 2, 'title': 'king of cricket', 'cricketername': 'Kohli'},
{'id': 3, 'title': 'god of cricket', 'cricketername': 'Sachin'}
]>

Retrieve Specific Fields:

Let's see how can we fetch only 'title' of all cricketers

Python
cricketers = Cricketer.objects.values('title') 

Output:

<Queryset[
{'id':1, 'title': 'godfather of cricket'},
{'id': 2, 'title': 'king of cricket'},
{'id': 3, 'title': 'god of cricket'}
]>

Using values() for a Single Object

When working with a single object, we might need to retrieve just a specific set of fields instead of the whole model. The values() method works seamlessly for retrieving data from a single object when combined with methods like filter().

Example 1: Using filter() with values()

Python
cricketer = Cricketer.objects.filter(id=1).values('title', 'cricketername').first() 

Output:

{'id': 1, 'title': 'God father of cricket', 'cricketername': 'Dhoni'}

Here, filter() is used to retrieve the Cricketer object with id=1, and values() ensures that only the title and author fields are fetched from the database. The first() method is used to get the first (and only) result as a dictionary.

Example 2: Using get() with values()

The values() method is a attribute of a queryset not a instance of Model objects. So, we cannot use values() method with a single object.

We can access the fields directly without using values():

Python
cricketer = Cricketer.objects.get(id=1) cricketer_dict = {     'title': cricketer.title,     'name': cricketer.name } print(cricketer_dict) 

Output:

{'title': 'God father of cricket', 'cricketername': 'Dhoni'}


Conclusion

Django’s QuerySet.values() is an efficient way to retrieve specific fields from the database in the form of dictionaries, particularly useful when we don't need full model instances. For single objects, values() can help improve performance and reduce the memory footprint of your queries.

Key takeaways:

  • Use values() when we need a dictionary representation of specific fields.
  • Combine filter() with values() and first() to fetch specific fields for a single object.
  • Avoid get() with values() as it returns a model instance.
  • Use values() judiciously to optimize performance but remember it comes at the cost of losing access to model instance methods.

By mastering the use of values(), we can create more efficient queries and improve the performance of our Django applications, particularly when working with large datasets or optimizing API responses.


Next Article
Django QuerySet.values() for Single Object

S

smitzinzubj6u
Improve
Article Tags :
  • Python
  • Python Django
Practice Tags :
  • python

Similar Reads

    Django Query Set - get
    A QuerySet is a collection of data retrieved from the database. You can think of it as a list of objects. QuerySets make it easier to get only the data you need by letting you filter, sort, and organize your data early on before actually fetching it from the database.In this article, we will learn h
    3 min read
    Django Query Set - Order By
    order_by() method in Django QuerySets is used to sort query results based on one or more fields, either in ascending or descending order. This helps display data sorted by criteria like salary, name, date, etc., directly from the database query.In this article we will learn all about order_by method
    2 min read
    Count() vs len() on a Django QuerySet
    In Django, when working with database query sets, developers often need to determine the number of records that meet certain criteria. Django offers two primary ways to accomplish this: using the count() method on a QuerySet, or the Python built-in len() function. Each method has its specific use ca
    3 min read
    ObjectDoesNotExist Error in Django
    In this article we will discuss How to fix 'ObjectDoesNotExist', Django, a powerful web framework for Python, simplifies the process of building web applications. However, developers often encounter the 'ObjectDoesNotExist' exception, which arises when a query, executed through the get() method, fai
    5 min read
    Django values_list vs values
    In Django, when querying the database, the QuerySet API offers two powerful methods for fetching specific fields from the database: values() and values_list(). Both methods return query results in a more efficient format compared to fetching entire model instances, which is especially useful when we
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences