In Django, the get()
method is a function provided by the QuerySet API to retrieve a single record from the database based on specific criteria. It is used for precisely fetching one record that matches the given criteria, making it ideal when you expect to retrieve a single, unique result. The primary purpose of the get()
method is to retrieve a single record from the database. It expects to find exactly one matching record; otherwise, it raises exceptions.
- If the query does not match any records, it raises a
Model.DoesNotExist
exception. - If the query matches multiple records, it raises a
Model.MultipleObjectsReturned
exception.
Example, to get the Person
whose id
is 1 :
Person.objects.get(id=1)
Multiple conditions can also be passed as well in the get()
method while retrieving values :
Person.objects.get(first_name='Ed', last_name='Kool')
If no values are present satisfying the condition, then an exception would occur :
Person.objects.get(first_name='test')
The Exception would be like this :
raise self.model.DoesNotExist(
modeldemo.models.Person.DoesNotExist: Person matching query does not exist.
Or even if there are multiple records that matches a specific condition, an error would occur :
Person.objects.get(first_name__startswith='J')
The Exception would be like :
raise self.model.MultipleObjectsReturned(
modeldemo.models.Person.MultipleObjectsReturned: get() returned more than one Person -- it returned 4!
These exceptions needs to be handled in the code correctly, to ensure the smooth working of the website.
If you want to retrieve multiple records or don't know if the result is unique, consider using the filter()
method instead.