Hassan Baig Hassan Baig - 10 months ago 50
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

object for
owner_id = pk
in the table currently):



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


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
      # we have no object!  do something

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