1👍
Using only
or its counterpart defer
does not prevent accessing the deferred attributes. It only delays retrieval of said attributes until they are accessed. So take the following:
for theme in Theme.objects.all():
print theme.name
print theme.other_attribute
This will execute a single query when the loop starts. Now consider the following:
for theme in Theme.objects.only('name'):
print theme.name
print theme.other_attribute
In this case, the other_attribute
is not loaded in the initial query at the start of the loop. However, it is added to the model’s list of deferred attributes. When you try to access it, another query is executed to retrieve the value of other_attribute
. In the second case, a total of n+1 queries is executed for n Theme
objects.
The only
and defer
methods should only ever be used in advanced use-cases, after the need for optimization arises, and after proper analysing of your code. Even then, there are often workarounds that work better than deferring fields. Please read the note at the bottom of the defer
documentation.
0👍
If what you want is a single column, I think what you are looking for is .values()
instead of .only
.
- [Answer]-I am getting 400 BAD REQUEST in tastypie
- [Answer]-Taking as a parameter but not using in view
- [Answer]-Import app foreign key model class in another app model
- [Answer]-Dynamic search with django form
- [Answer]-Unable to get post data in a multipleChoiceField with django