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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With