Django QuerySet Get

Retrieving single objects from the database

🎯 What is get()?

The get() method retrieves a single object from the database that matches your criteria. It's perfect when you need exactly one record, like finding a user by ID.


# Get a single book by ID
from myapp.models import Book

book = Book.objects.get(id=1)
print(book.title)
                                    

Output:

Python Guide

Key get() Concepts

1️⃣

Single Object

Returns exactly one object

book = Book.objects.get(id=5)
print(book.title)
🔑

Primary Key

Often used with unique identifiers

# Using pk (primary key)
book = Book.objects.get(pk=1)
⚠️

Raises Exceptions

Errors if not found or multiple found

# DoesNotExist exception
try:
    book = Book.objects.get(id=999)
except Book.DoesNotExist:
    print("Not found")
🔍

Unique Fields

Works with any unique field

# Get by unique field
book = Book.objects.get(
    isbn='978-0-123456-78-9'
)

🔹 Basic get() Usage

The get() method is straightforward - pass the field name and value you're looking for. It returns the model instance if found, making it easy to access all the object's attributes.

# models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    isbn = models.CharField(max_length=13, unique=True)
    price = models.DecimalField(max_digits=6, decimal_places=2)

# views.py
from myapp.models import Book

# Get book by ID
book = Book.objects.get(id=1)
print(f"Title: {book.title}")
print(f"Author: {book.author}")
print(f"Price: ${book.price}")

Output:

Title: Python Guide

Author: John Doe

Price: $29.99

🔹 Using pk (Primary Key)

Django provides a convenient pk shortcut that always refers to the primary key field, regardless of what you named it. This makes your code more flexible and easier to maintain.

# Using pk instead of id
from myapp.models import Book

# These are equivalent
book1 = Book.objects.get(id=1)
book2 = Book.objects.get(pk=1)

# pk works even if primary key has different name
user = User.objects.get(pk=5)  # Works regardless of field name

print(book1.title)
print(book2.title)

Output:

Python Guide

Python Guide

🔹 Handling Exceptions

The get() method raises exceptions when things go wrong. DoesNotExist is raised when no object matches, and MultipleObjectsReturned when more than one matches. Always handle these exceptions in production code.

from myapp.models import Book
from django.core.exceptions import ObjectDoesNotExist

# Handle DoesNotExist exception
try:
    book = Book.objects.get(id=999)
    print(book.title)
except Book.DoesNotExist:
    print("Book not found!")

# Handle MultipleObjectsReturned
try:
    book = Book.objects.get(author="John Doe")
except Book.MultipleObjectsReturned:
    print("Multiple books found!")

# Generic exception handler
try:
    book = Book.objects.get(pk=100)
except ObjectDoesNotExist:
    print("Object does not exist")

Output:

Book not found!

🔹 get() with Multiple Conditions

You can pass multiple parameters to get() to narrow down your search. All conditions must be met for the object to be returned, similar to an AND operation in SQL.

from myapp.models import Book

# Get book with multiple conditions
try:
    book = Book.objects.get(
        author="John Doe",
        published=True,
        price=29.99
    )
    print(f"Found: {book.title}")
except Book.DoesNotExist:
    print("No matching book found")
except Book.MultipleObjectsReturned:
    print("Multiple books match criteria")

Output:

Found: Python Guide

🔹 get_or_create() Method

Django provides get_or_create() as a convenient shortcut that tries to get an object, and creates it if it doesn't exist. This is useful for ensuring data exists without duplicate code.

from myapp.models import Book

# Get existing or create new
book, created = Book.objects.get_or_create(
    isbn='978-0-123456-78-9',
    defaults={
        'title': 'New Book',
        'author': 'Jane Smith',
        'price': 39.99
    }
)

if created:
    print(f"Created new book: {book.title}")
else:
    print(f"Found existing book: {book.title}")

Output:

Created new book: New Book

🧠 Test Your Knowledge

What happens if get() finds multiple objects?