Nuno_147
Nuno_147

Reputation: 2913

Django queries on querysets performance

I have a Model and I am doing a query :

my_objects = Model.objects.filter(user = request.user)

now over my_objects I am doing :

obj = my_objects.get(user = x )

I am trying to understand if my .get over my_objects will not generate another query to the database and will only work on the filter output ? or it will be generating another query.

Upvotes: 0

Views: 592

Answers (1)

levi
levi

Reputation: 22697

If Model isnt User instance, it will hit database again, because User in that case is a related object, if you dont want hit again the database, use select_related() and filter by yourself obj:

"will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query"

my_objects = Model.objects.select_related().filter(user = request.user)

see more info here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related

EDIT: I forgot mention that QuerySet in django are lazy, actually don't hit the db until you evaluate the queryset, these are methods that force to evaluate a queryset : methods

Upvotes: 1

Related Questions