Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : object_set vs filter

Consider the following:

I have an images model which uses a brand as a foreign key.

brand = Brand.objects.get(id = whatever)

I could retrieve all the images associated with that model with either of these ways:

images = Image.objects.filter(brand = brand)

or

images = brand.image_set.all()

From a performance standpoint, which one of these is faster?

like image 903
DGDD Avatar asked Oct 16 '15 20:10

DGDD


1 Answers

There won't be any performance differences. In both cases the generated SQL query will be the same.

Therefore which one you choose is a matter of taste. Personally, I prefer

images = Image.objects.filter(brand=brand)

because it is very clear that you are returning a queryset of images.

However, you could argue that

images = brand.image_set.all()

is safer, because the brand filtering is automatic, whereas in the other way you could forget to filter on brand=brand.

like image 176
Alasdair Avatar answered Nov 15 '22 01:11

Alasdair