Django QuerySets: Introduction and Using get()
Last Updated : 22 May, 2025
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 how to get data from a model into a QuerySet using get method:
get() Method: Retrieve a Single Object
The get() method returns exactly one object that matches the conditions you provide. It is useful when you expect only one result.
If no object matches, Django raises a DoesNotExist exception. If more than one object matches, it raises a MultipleObjectsReturned exception.
Syntax
Model.objects.get(**kwargs)
- Model is your Django model.
- kwargs are the conditions used to find the object.
Example: Using get() with a Book Model
Suppose we have a Book model with fields like title and author. To get the book titled "The Great Gatsby":
Python from app.models import Book try: book = Book.objects.get(title='The Great Gatsby') # Use the book object here except Book.DoesNotExist: print("No book found with that title.") except Book.MultipleObjectsReturned: print("Multiple books found with that title.")
Using Multiple Conditions (AND)
You can provide multiple filters to narrow down results. For example, suppose we have multiple books with title "The Great Gatsby", but we only need results for the book to be written by author "F. Scott Fitzgerald", then we provide multiple query conditions:
Python try: book = Book.objects.get(title='The Great Gatsby', author='F. Scott Fitzgerald') except Book.DoesNotExist: print("No matching book found.") except Book.MultipleObjectsReturned: print("More than one book matches your query.")
Django treats these conditions as an AND operation, returning the object that matches all conditions.
Using Primary Key with get()
Fetching objects by their primary key (usually id) is common:
book = Book.objects.get(pk=1) # Get book with primary key 1
Practical Uses of get()
- Authenticating users by username or email.
- Retrieving records using unique fields like primary keys.
- Getting exact matches when you expect one record.
Using get() in the Django Shell
The Django shell is an interactive Python environment that lets you experiment with your Django models and QuerySets in real-time. It’s a great tool for testing database queries, exploring your data, and debugging without needing to write views or templates first.
Example: Fetching a Book Object Using get()
Consider the book model we created earlier and we need to fetch data from it using Python Shell, here's how we can do it:
1. Activate the Shell:
python manage.py shell
2. Use the following commands:
>>> from app.models import Book
>>> book = Book.objects.get(id=2)
>>> print(book)
This should print the details of book with id = 2.
Snapshot of the terminal shellNote: If no book with id=3 exists, a DoesNotExist exception will be raised; if multiple entries matched (unlikely with primary keys), a MultipleObjectsReturned exception would occur.
Similar Reads
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
Extracting SQL Queries from Django QuerySets Django, a high-level Python web framework, simplifies the development of secure and maintainable websites. One of its powerful features is the Object-Relational Mapping (ORM) system, which allows developers to interact with the database using Python code instead of raw SQL. However, there are times
3 min read
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 QuerySet.values() for Single Object 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 v
3 min read
How to combine multiple QuerySets in Django? QuerySets allow you to filter, order, and manipulate data from your database using a high-level Pythonic syntax. However, there are situations where you may need to combine multiple QuerySets into a single QuerySet to work with the data more efficiently. This article will explore various methods to
5 min read
How to Output Django QuerySet as JSON In Django, a common task for web developers is to return data in JSON format, especially when working with APIs. A Django QuerySet, which is a collection of database queries, can be serialized and output as JSON. This article will guide us through how to output a Django QuerySet as JSON using two me
4 min read