Skip to content
thesarfo

Note

Retrieving Objects

Using .all() and .get(), and safer alternatives to try/except for handling missing objects with filter().first() and .exists().

views 0

The first method for retrieving objects is the

Product.objects.all() #returns all objects in the product table
Product.objects.get(pk=1) #returns a single object with id=1, or pk=1. This one returns an object not a queryset.

One thing is that, sometimes when you are retrieving an object that doesnt exist, like Product.objects.get(pk=0), our program will crash and we will get an error. So it is best practice to wrap our retrieval inside a try except block. see below

from django.shortcuts import render
from django.core.exceptions import ObjectDoesNotExist
from store.models import Product
# Create your views here.
def say_hello(request):
try:
product = Product.objects.get(pk=0)
except ObjectDoesNotExist:
pass
return render(request, 'hello.html', {'name': 'Ernest'})

This time we won’t get an exception.

But our try catch looks a bit ugly rn. And there’s an even better way of retrieving an object without getting an error or using a try catch. See below

def say_hello(request):
# product will be none
product = Product.objects.filter(pk=0).first()
return render(request, 'hello.html', {'name': 'Ernest'})

In the above code, we filter the product with pk=0 therefore generating a query, and further return the first method of the queryset. If the queryset is empty, the first method will return none. Therefore, in this case, product will be none and we wont get an exception.

Sometimes we want to check the existence of a object. see below

def say_hello(request):
# returns a boolean value = false.
product = Product.objects.filter(pk=0).exists()
return render(request, 'hello.html', {'name': 'Ernest'})