Django - 按属性将查询划分为子组

时间:2014-09-17 20:40:43

标签: python django django-queryset choicefield

我的模型看起来像这样:

class ListEntry(models.Model):
    STATUS_CHOICES = (
        ('PL', _('Playing')),
        ('CO', _('Completed')),
        ('OH', _('On-hold')),
        ('DR', _('Dropped')),
        ('WA', _('Want to play')),
    )
    user = models.ForeignKey(User)
    game = models.ForeignKey(Game)
    status = models.CharField(_('Status'), max_length=2,
                              choices=STATUS_CHOICES)

在我的观看中,我正在按用户过滤条目:

class GameListByUserView(ListView):
    model = ListEntry
    template_name = 'game_list_by_user.html'

    def get_queryset(self):
        self.user_profile = get_object_or_404(User, username=self.kwargs['slug'])
        return ListEntry.objects.filter(user=self.user_profile)

    def get_context_data(self, **kwargs):
        context = super(GameListByUserView, self).get_context_data(**kwargs)
        context['user_profile'] = self.user_profile
        return context

我现在要做的是将此查询(ListEntry.objects.filter(user=self.user_profile))拆分为子组,具体取决于status属性,因此呈现的模板如下所示:

UserFoo's list
=========================

Playing

Game 1
Game 2
Game 3


Completed

Game 4
Game 5
Game 6

我知道我可以这样做:

q = ListEntry.objects.filter(user=self.user_profile)
games_dict = {}
games_dict['playing'] = q.filter(status='PL')
games_dict['completed'] = q.filter(status='CO')

依此类推,并迭代模板中的键。或(在模板中):

{% for s in status_choices %}
  {% for entry in object_list %}
    {% if entry.status == s %}
      Render things
    {% endif %}
  {% endfor %}
{% endfor %}

但是,如果没有按状态获取子查询,并且没有多次遍历对象列表,那么有没有更好的,优化的方法来执行此操作而不会访问数据库?

1 个答案:

答案 0 :(得分:2)

您正在寻找regroup filter

{% regroup object_list by status as games_list %}

<ul>
{% for game in games_list %}
    <li>{{ game.grouper }}
    <ul>
        {% for item in game.list %}
          <li>{{ item}}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

您可能需要自定义元素渲染的方式,但我会让您自己解决这个问题。