difference between values() and only()
Assuming Blabla
has the fields in your question, as well as field4
,
Blabla.objects.only('field1', 'field2', 'field3')[0].field4
will return the value of that object's field4
(with a new database query to retrieve that info), whereas
Blabla.objects.values('field1', 'field2', 'field3')[0].field4
will give
AttributeError: 'dict' object has no attribute 'field4'
This is because .values()
returns a QuerySet
that returns dictionaries, which is essentially a list of dicts, rather than model instances (Blabla
).
.values()
gives you "less than a model"; the items it returns are closer to dictionaries than full models, which means you don't get the model attributes but you also don't have to initialize full models.
.only()
restricts the field list in the SQL to specific fields you care about, but still initializes a full model; it defers loading of the other fields until you access them (if at all).