考虑到Django文档中的以下简化模型,我想返回所有作者的列表,这些作者根据他们最近的条目或过去某个日期之前的评级分组。
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
class Entry(models.Model):
headline = models.CharField(max_length=255)
pub_date = models.DateTimeField()
mod_date = models.DateTimeField()
authors = models.ForeignKey(Author)
rating = models.IntegerField()最后,我想把它变成一个python字典,比如:{1star:(author1,author2),2star:(author3,author4,author5)...}。
一种想法是返回所有条目,然后使用itertools.groupby操作大型数据集。有没有人能推荐一个更干净的替代方案?
发布于 2011-08-09 16:17:34
实际上,你可以在你的模板中完全做到这一点。像这样的东西应该是有效的:
**Views.py**
authors = Author.objects.all()
**Template**
{% regroup authors by rating_set.all|last as rating_list %}
{% for rating in rating_list %}
<b>{{ rating.grouper }}</b><br>
{% for author in rating.list %}
{{ author.name }}<br>
{% endfor %}
{% endfor %}基本上,此方法使用regroup模板标记按评级对所有作者进行分组。last过滤器应该会在每个作者的评分列表中为您提供最新的评分。在那之后,这只是一个基本的重组练习,通过评级将其分解,并显示每个评级的所有作者。
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#regroup
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#last
https://stackoverflow.com/questions/6976792
复制相似问题