Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 742
Hassan Baig Avatar asked Oct 31 '25 19:10

Hassan Baig


1 Answers

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

like image 85
Aswin Kumar K P Avatar answered Nov 03 '25 10:11

Aswin Kumar K P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!