Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between values() and only()

what's the difference between using:

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

and

Blabla.objects.only('field1', 'field2', 'field3') 
like image 493
Jonatas CD Avatar asked Aug 15 '12 18:08

Jonatas CD


People also ask

What is the difference between values and values_list?

"values()" returns a QuerySet of dictionaries. "values_list()" returns a QuerySet of tuples. "values_list()" with "flat=True" returns a QuerySet of values.

What is the difference between value and object?

A value is a more abstract concept than an object. Like those mentioned in comments, the difference/relationship between a value and an object is similar to that between water and a cup. You need a container, which in this case is a cup, to hold the water, or it will leak.

What is flat in Django?

flat parameterWhen grabbing a single values from the db, you can pass`flat=true` which will just give you back single values, instead of tuples: >>> queryset = Book. objects.


1 Answers

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).

like image 176
supervacuo Avatar answered Oct 02 '22 07:10

supervacuo