The difference between () and only ()

what's the difference between use:

Blabla.objects.values('field1', 'field2', 'field3') 

and

 Blabla.objects.only('field1', 'field2', 'field3') 
+6
source share
3 answers

Assuming Blabla has fields in your question as well as field4 ,

 Blabla.objects.only('field1', 'field2', 'field3')[0].field4 

will return the value of this field4 object (with a new database query to get this information), whereas

 Blabla.objects.values('field1', 'field2', 'field3')[0].field4 

will give

 AttributeError: 'dict' object has no attribute 'field4' 

This is because .values() returns a ValuesQuerySet based on an existing QuerySet , which is essentially a list of dicts (in the sense that a regular QuerySet is a list of Blabla objects).

+4
source

.values() gives you "less than model"; the elements that it returns are closer to dictionaries than full models, which means you don't get model attributes, but you also don't need to initialize full models.

.only() limits the list of fields in SQL to specific fields that you are interested in, but still initializes the full model; it defers loading other fields until you get access to them (if at all).

+3
source

values() returns a special ValueQuerySet - which, when repeated, returns dictionaries representing the model. It does not return model objects.

only() is a way to limit returned columns and ensure that only those columns are returned immediately, so it is sometimes called the opposite of defer() . This is equivalent to the SELECT foo, bar, zoo FROM than regular SELECT [all columns] FROM . It will return a QuerySet , which may be constrained.

+1
source

Source: https://habr.com/ru/post/922972/


All Articles