📜  values django - Python (1)

📅  最后修改于: 2023-12-03 15:05:47.678000             🧑  作者: Mango

Values() in Django - Python

In Django, the values() method returns a QuerySet that contains dictionaries. Each dictionary represents a row in the database table(s) that is being queried, but only contains the specified fields in the values() method.

Syntax

The syntax for values() method is:

values(*fields, **expressions)

Where fields are names of fields to retrieve. If no fields are provided, all fields will be retrieved.

expressions are used to calculate values that aren’t normally part of the query. These expressions can be simple mathematical expressions.

Example

Here's an example of values() method:

from myapp.models import MyModel

my_values = MyModel.objects.values('field_1', 'field_2', calculated_field=F('field_1') + F('field_2'))

In this example, MyModel is a Django model and the values() method is used to get the values for field_1 and field_2, as well as a calculated field that adds field_1 and field_2.

The values() method returns a QuerySet containing dictionaries that look like this:

[
    {'field_1': 1, 'field_2': 2, 'calculated_field': 3},
    {'field_1': 3, 'field_2': 4, 'calculated_field': 7},
    ...
]
Conclusion

In conclusion, values() method in Django allows you to get a QuerySet containing dictionaries that represent rows in a database table with only the specified fields, and calculated fields if you want. This method is very useful when you only need specific fields from your database, rather than all of them.