Login

get_object_or_none

Author:
azwdevops
Posted:
May 14, 2025
Language:
Python
Version:
5.0
Score:
1 (after 1 ratings)

This utility is useful when you want to safely retrieve a single object from the database without having to wrap get() in a try/except block every time.

It also supports query optimization via select_related and prefetch_related, making it ideal for performance-conscious applications.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def get_object_or_none(model_class, select_related=None, prefetch_related=None, **filters):
    """
    Safely fetch a single object from the database using Django ORM, or return None
    if it does not exist. Optionally supports select_related and prefetch_related
    to optimize query performance for related fields.

    Args:
        model_class (models.Model): The Django model class to query.
        select_related (Iterable[str], optional): List or tuple of fields for select_related.
        prefetch_related (Iterable[str], optional): List or tuple of fields for prefetch_related.
        **filters: Keyword arguments representing query filter conditions.

    Returns:
        instance (model_class | None): The object if found, or None if not found.
    
    Raises:
        MultipleObjectsReturned: If the query matches more than one object.
    
    Example:
        from myapp.models import User

        user = get_object_or_none(User, select_related=["profile"], id=5)

        if user:
            print("User found:", user.username)
        else:
            print("User not found.")
    """
    try:
        queryset = model_class.objects

        if select_related:
            queryset = queryset.select_related(*select_related)

        if prefetch_related:
            queryset = queryset.prefetch_related(*prefetch_related)

        return queryset.get(**filters)
    except model_class.DoesNotExist:
        return None

More like this

  1. Mask sensitive data from logger by agusmakmun 3 months ago
  2. Template tag - list punctuation for a list of items by shapiromatron 1 year, 5 months ago
  3. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 5 months ago
  4. Serializer factory with Django Rest Framework by julio 2 years ago
  5. Image compression before saving the new model / work with JPG, PNG by Schleidens 2 years ago

Comments

Please login first before commenting.