[英]How do I find each instance of a model in Django
I am trying to iterate through each instance of a model I have defined.我正在尝试遍历我定义的 model 的每个实例。
Say I have the following in models.py
, under the people
django app:假设我在
models.py
中有以下内容,在people
django 应用程序下:
class foo(models.Model):
name = models.CharField(max_length=20, default="No Name")
age = models.PositiveSmallIntegerField(default=0)
And I have populated the database to have the following data in foo:我已经填充了数据库以在 foo 中包含以下数据:
Now I want to work out the average age of my dataset.现在我想计算出我的数据集的平均年龄。 In another part of the program (outside the
people
app, inside the project
folder), in a file called bar.py
that will be set up to run automatically every day at a specific time, I calculate this average.在程序的另一部分(在
people
应用程序之外,在project
文件夹内),在一个名为bar.py
的文件中,该文件将被设置为每天在特定时间自动运行,我计算了这个平均值。
from people.models import foo
def findAverageAge():
total = 0
for instance in //What goes here?// :
total += instance.age
length = //What goes here, to find the number of instances?//
average = total / length
return average
print(findAverageAge)
In the code above, the //What goes here?// signifies I don't know what goes there and need help.在上面的代码中,//What goes here?// 表示我不知道那里有什么需要帮助。
You can retrieve all elements with.all()
[Django-doc] :您可以使用
.all()
[Django-doc]检索所有元素:
from people.models import foo
def findAverageAge():
total = 0
qs = foo.objects.all()
for instance in :
total += instance.age
length = len(qs)
average = total / length
return average
print(findAverageAge())
But you should not calculate the average at the Django/Python level.但是你不应该计算 Django/Python 级别的平均值。 This requires retrieving all records, and this can be quite large.
这需要检索所有记录,而且这可能非常大。 A database itself can calculate the average, and this is (normally) done in a more efficient way.
数据库本身可以计算平均值,这(通常)以更有效的方式完成。 You can
.aggregate(…)
[jango-doc] on the queryset with:您可以在查询集上
.aggregate(…)
[jango-doc] :
from people.models import foo
def findAverageAge():
return foo.objects.aggregate(
avg_age=Avg('age')
)
['avg_age'] or 0
print(findAverageAge())
You should make a management command however: this will load the Django apps, and also makes it more convenient to run command with parameters, etc.但是,您应该创建一个管理命令:这将加载 Django 应用程序,并且还可以更方便地使用参数等运行命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.