通过 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)
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'))
但是 ORM 调用仍然会为每个 Lecture 返回一个结果,并在 Python 中减少它,因此对于大量的 Lecture 集,它可能会增长缓慢。
I have this Django model:
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)
term
can be either 1
or 2
(spring or fall). Now I want to list all terms for which there are lectures, e.g. something like ((2007, 2), (2008, 1), (2008, 2), (2009, 1), (2009, 2), (2010, 1))
. The list doesn't have to be sorted. Is it possible to generate this list through the ORM efficiently? The best solution I found is:
term_list = set(Lecture.objects.values_list('year', 'term'))
But that ORM call still returns a result for every Lecture
and reduces it in Python, so it could grow slow with a large set of Lecture
s.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果数据库中有所有数据,那么它就可以工作。但如果没有数据,您应该自己生成。
直接从数据库中获取(但如果不在数据库中,则不会返回所有组合):
if you have all the data in the database, then it will work. but if data is not there, you should generate it yourselves.
directly from the database (but will not return all the combinations if not in the database):
您可能正在寻找 distinct() 和值()。
You are probably looking for a combination of distinct() and values().