Understanding the difference between .get and .first in Django
Posted on Fri 21 May 2021 in Better Django
When retrieving a single record in Django, the ORM offers two possible methods: .get()
and .first()
. Let's learn how each one works and when to use them.
Get
Django's most basic way to retrieve a single record is the .get() method. It is used as follows:
burger = Menu.objects.get(name="Beef Burger")
Quick facts about .get()
:
-
It retrieves only one record.
-
If no record exists that meets the given criteria, it raises a
DoesNotExist
exception. -
If more than one record with the given criteria exists, it raises a
MultipleObjectsReturned
exception.
First
A different way to get one record is …
Continue reading