only(*fields)
The only()
method is more or less the opposite of defer()
. You call it with the fields that should not be deferred when retrieving a model. If you have a model where almost all the fields need to be deferred, using only()
to specify the complementary set of fields can result in simpler code.
Suppose you have a model with fields name
, age
and biography
. The following two querysets are the same, in terms of deferred fields:
Person.objects.defer("age", "biography") Person.objects.only("name")
Whenever you call only()
it replaces the set of fields to load immediately. The method’s name is mnemonic: only those fields are loaded immediately; the remainder are deferred. Thus, successive calls to only()
result in only the final fields being considered:
# This will defer all fields except the headline. Entry.objects.only("body", "rating").only("headline")
Since defer()
acts incrementally (adding fields to the deferred list), you can combine calls to only()
and defer()
and things will behave logically:
# Final result is that everything except "headline" is deferred. Entry.objects.only("headline", "body").defer("body") # Final result loads headline and body immediately (only() replaces any # existing set of fields). Entry.objects.defer("body").only("headline", "body")
All of the cautions in the note for the defer()
documentation apply to only()
as well. Use it cautiously and only after exhausting your other options.
Using only()
and omitting a field requested using select_related()
is an error as well.
Please login to continue.