Hassan Baig Hassan Baig - 1 year ago 66
SQL Question

filter vs get performance in Django ORM, when there's only 1 object available for retrieval

I have a Django application.
Solely in terms of ORM/query/DB performance, are the following ways of retrieving an object equivalent (i.e. in a situation where there was just a single

Car
object for
owner_id = pk
in the table currently):

Car.objects.get(owner_id=pk)

Car.objects.filter(owner_id=pk).latest('id')


owner
is a foreign key relationship, hence is a DB index. Are the SQL queries produced equivalent (or the same)?

Answer Source

Since you are using the Foreign key, get() and filter() will give the same performance.

How you see get()

objs = Car.objects.get(owner_id=pk)

How get() is actually implemented by Django

objs = Car.objects.filter(owner_id=pk)
   if len(objs) == 1:
      obj = objs[0]
   else if len(objs) > 1:
      # Multiple objects returned
   else: 
      # we have no object!  do something
      pass

For your case, I would recommend using get() because

  1. you can be sure that only one element is returned

  2. it is designed for this purpose