Reputation: 12187
I have a model like this...
class Model():
header = CharField()
tagline = CharField()
menubutton1 = Charfield()
menubutton2 = CharField()
page1 = CharField()
page2 = CharField()
The header and the tagline go into every template, but the page1 and page2 texts would only go into their corresponding pages. I do a query and then include these in a lot of different views, so I am wondering if all the data is pulled from the db and actually transferred when the query is made or when the data is called in the template?
Upvotes: 2
Views: 40
Reputation: 55448
QuerySet
s are lazy ( constructed, filtered, sliced, and generally passed around without actually hitting the database), but once a model is fetched it'll load all the fields of the model from the database.
defer()
However you can use .defer()
on the queryset to exclude a field from being loaded from the database when the queryset is evaluated. It is effectively deferring the loading of those fields.
In some complex data-modeling situations, your models might contain a lot of fields, some of which could contain a lot of data (for example, text fields), or require expensive processing to convert them to Python objects. If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.
So e.g. you want the queryset that goes in as the context for page 1 to exclude the field page2
models_for_page_1 = Model.objects.defer('page2')
When the above queryset gets evaluated, it will fetch all fields except page2
Each deferred field will be retrieved from the database if you access that field (one at a time, not all the deferred fields at once).
If you don't access page2
on the model from that queryset with the deferred loading for that field, it will never be loaded, but if you do access it, it'll be loaded separately when you access it.
So as long as page 1 never accesses Model.page2
this should do what you want.
only()
This is kind of the complement of defer()
, it only fetches the fields listed, so for you e.g.:
models_for_page_1 = Model.objects.only('header', 'tagline', ..., 'page1')
defer()
/only()
and values()
defer()
and only()
return model instances, while values()
returns dictionaries with the values
Upvotes: 2