Ben*_*end 2 python django django-orm
我有这个Django模型:
class Lecture(models.Model):
lecture_number = models.CharField(_('lecture number'), max_length=20)
title = models.CharField(_('title'), max_length=100)
term = models.IntegerField(_('term'), choices=TERM, db_index=True)
year = models.IntegerField(_('year'), db_index=True)
Run Code Online (Sandbox Code Playgroud)
term可以是1或2(春天或秋天).现在我想列出有讲座的所有术语,例如((2007, 2), (2008, 1), (2008, 2), (2009, 1), (2009, 2), (2010, 1)).该列表不必排序.是否可以有效地通过ORM生成此列表?我找到的最佳解决方案是:
term_list = set(Lecture.objects.values_list('year', 'term'))
Run Code Online (Sandbox Code Playgroud)
但是,ORM调用仍会返回每个结果Lecture并在Python中减少它,因此它可能会因为大量的Lectures而变慢.
如果您拥有数据库中的所有数据,那么它将起作用.但如果没有数据,你应该自己生成.
In [1]: import itertools
In [2]: list(itertools.product((2006,2007,2008), (1,2)))
Out[2]: [(2006, 1), (2006, 2), (2007, 1), (2007, 2), (2008, 1), (2008, 2)]
Run Code Online (Sandbox Code Playgroud)
直接来自数据库(但如果不在数据库中则不会返回所有组合):
In [1]: from django.db import connection
In [2]: Lecture.objects.values_list('year','term').distinct()
Out[2]: [(2001, 1), (2001, 2), (2002, 1), (2002, 2), (2003, 1), (2003, 2), (2004, 1), (2004, 2)]
In [3]: connection.queries
Out[3]:
[{'sql': u'SELECT DISTINCT "backend_lecture"."year", "backend_lecture"."term" FROM "backend_lecture" LIMIT 21', 'time': '0.001'}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
699 次 |
| 最近记录: |