📅  最后修改于: 2023-12-03 15:14:44.882000             🧑  作者: Mango
In Django, the Avg
function is used to calculate the average value of a set of values in a Django Model field. This function is available in the django.db.models
module and is used with a QuerySet to calculate the average value of a numerical field.
To use the Avg
function in your Django project, you must first import it from django.db.models
.
from django.db.models import Avg
You can then use the Avg
function in a QuerySet to calculate the average value of a numerical field.
average = MyModel.objects.aggregate(Avg('my_numerical_field'))
In the code above, replace MyModel
with the name of the Django model you want to query and my_numerical_field
with the name of the numerical field you want to calculate the average value for.
The Avg
function returns a dictionary-like object that contains the average value of the numerical field. You can access the average value by calling the field name as a key from the dictionary.
# example using the average value
average_value = average['my_numerical_field__avg']
Note that the dictionary key includes __avg
appended to the field name in order to access the average value.
from django.db.models import Avg
from myapp.models import MyModel
# Get the average value of a numerical field in MyModel
average = MyModel.objects.aggregate(Avg('my_numerical_field'))
# Access the average value
average_value = average['my_numerical_field__avg']
Using the Avg
function in Django is a simple and powerful way to calculate the average value of a numerical field in a Django model. By importing the function from django.db.models
and using it with a QuerySet, you can quickly and easily retrieve the average value of any numerical field in your Django app.