0
0
Djangoframework~5 mins

get() for single objects in Django

Choose your learning style9 modes available
Introduction

The get() method helps you find one specific item in your database quickly and easily.

When you want to find a user by their unique ID.
When you need to get a single product by its exact name.
When you want to fetch a single blog post by its slug.
When you are sure only one item matches your search.
When you want to avoid getting a list and just want one object.
Syntax
Django
ModelName.objects.get(field_name=value)

get() returns exactly one object or throws an error if none or more than one are found.

Use unique fields or filters that return only one result.

Examples
Finds the user with ID 5.
Django
user = User.objects.get(id=5)
Finds the product named 'Coffee Mug'.
Django
product = Product.objects.get(name='Coffee Mug')
Finds the blog post with the slug 'my-first-post'.
Django
post = BlogPost.objects.get(slug='my-first-post')
Sample Program

This example tries to find one book titled 'Django Basics'. It prints the book's title and author if found. If no book or multiple books are found, it prints a message.

Django
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

# Imagine these books are saved in the database:
# Book(title='Django Basics', author='Alice')
# Book(title='Python Tips', author='Bob')

# Fetch a single book by title
try:
    book = Book.objects.get(title='Django Basics')
    print(f"Found book: {book.title} by {book.author}")
except Book.DoesNotExist:
    print("No book found with that title.")
except Book.MultipleObjectsReturned:
    print("More than one book found with that title.")
OutputSuccess
Important Notes

If no object matches, get() raises DoesNotExist error.

If more than one object matches, it raises MultipleObjectsReturned error.

Always handle these exceptions to avoid crashes.

Summary

get() finds exactly one object matching your filter.

It raises errors if zero or many objects match.

Use it when you expect only one result and want easy access to that object.