[Django ORM] Difference between values () and only ()

A story that fits in with a values () error in Django ORM

Django ORM has similar methods, <Model> .objects.values () and <Model> .objects.only (), values () and ʻonly ()`, but a little I was addicted to it, so as a memorandum.

The origin of this is that when I wrote a code like ↓, I got the following error.

president1 = Company.objects.values(*fields)[0].president
# =>error: AttributeError: 'dict' object has no attribute 'president'

Here, from the model Company, using thevalues ()method of Django ORM, I'm trying to get the value of the president field of the first element of a queryset (like a Python list with an iterable data type that contains multiple objects) that was generated by extracting only certain fields ..

However, at runtime I got the error ʻAttribute Error:'dict' object has no attribute'president'`.

Even after reviewing the model definition, I found out that the field president does exist, but this is strange. difference between values () and only () was helpful.

version

values () returns ValuesQuerySet instead of QuerySet

According to the reference article, the values () method returns an object of the data type ValuesQuerySet. Based on QuerySet, it returns ** an array of elements converted from object fields into a dictionary (= ValuesQuerySet) **.

In other words, in the above code, I was trying to retrieve field data from the dictionary {'president':'xxx', ...} using .president, so I got an error.

Since it is a dictionary, using ['president'] means that no error occurred. When you read the error message, it says 'dict' object. ..

Using ʻonly ()returnsQuerySet`

So, if you want QuerySet like this case, you can use ʻonly ()` [^ 1]. This time, the element is not a dictionary, but an instance of the class is returned properly, so no error occurs.

By the way, QuerySet is iterable, but be careful because the data type is different from list (because it is similar, I sometimes get hooked).

When converting a query set to a list, it can be converted with ** list (QuerySet object) **.

[^ 1]: Only specified fields can be extracted. Used for performance tuning. Conversely, you can use defer () to exclude the specified field.

Recommended Posts

[Django ORM] Difference between values () and only ()
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Difference between regression and classification
Difference between np.array and np.arange
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
Difference between java and python (memo)
Difference between list () and [] in Python
Difference between SQLAlchemy filter () and filter_by ()
Difference between == and is in python
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Difference between Numpy randint and Random randint
Difference between sort and sorted (memorial)
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Difference between SQLAlchemy flush () and commit ()
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
[Xg boost] Difference between softmax and softprob
difference between statements (statements) and expressions (expressions) in Python
Difference between PHP and Python finally and exit
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Difference between linear regression, Ridge regression and Lasso regression
[Python] Difference between class method and static method
Difference between docker-compose env_file and .env file
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
speed difference between wsgi, Bottle and Flask
Difference between numpy.ndarray and list (dimension, size)
Difference between ls -l and cat command
Difference and compatibility verification between keras and tf.keras # 1
Difference between using and import on shield language
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
About the difference between PostgreSQL su and sudo
What is the difference between Unix and Linux?
Consideration of the difference between ROC curve and PR curve
The rough difference between Unicode and UTF-8 (and their friends)
Can BERT tell the difference between "candy (candy)" and "candy (rain)"?
Difference between Ruby and Python in terms of variables
What is the difference between usleep, nanosleep and clock_nanosleep?
Difference between Numpy (n,) and (n, 1) notation [Difference between horizontal vector and vertical vector]
Difference between return, return None, and no return description in Python
How to use argparse and the difference between optparse
Center difference and forward difference
Between parametric and nonparametric
Django --models.py and admin.py
What is the difference between a symbolic link and a hard link?
Python module num2words Difference in behavior between English and Russian
Understand the difference between cumulative assignment to variables and cumulative assignment to objects
List concatenation method in python, difference between list.extend () and “+” operator
Difference between SQLAlchemy back_populates and backref and when neither is used
The difference between foreground and background processes understood by the principle
Relationship between Bound / Unbound and initial value of Django2 Form
Summary of Differences Between Ruby on Rails and Django ~ Basics ~