按位置分组并在模板中分组

时间:2019-01-20 18:09:15

标签: django python-3.x django-templates

我尝试显示db中的数据并将其放在正确的标题下。

models.py

class Game(models.Model):
    location= models.ForeignKey('location', on_delete=models.CASCADE')
    group = models.IntegerField()        
    firstname = models.CharField()
    surname = models.CharField()

views.py

class group(generic.CreateView):
    template_name = 'group.html'

    def get(self, request, *args, **kwargs):
        game = Game.objects.filter(location__type__pk=kwargs['pk']).order_by('location__pk', 'group')            
        context = {
            'game': game,
        }
        return render(request, self.template_name, context)

让我们说“组”可以像A,B,C等。

在模板中,我希望将其显示为

Location Foo
  Group A
    Jonas Andersson
    Lisa Silverspoon
  Group B
    Sven Bohlin
    Göran Lantz

Location Bar
  Group A
    Mia Milakovic
    Lars Larsson
  Group B
    Anna Annasdotter

我尝试了许多for循环的变体,但都没有成功。

有可能吗?你能做到吗?

2 个答案:

答案 0 :(得分:0)

您可以使用模板过滤器regroup

{% regroup games by location as games_list %}

{% for location, games in country_list %}
    {{ location }}
    {% for game in games %}
       {{ game.group }}
       ...
    {% endfor %}
{% endfor %}

注意:这里的游戏是一个列表,这就是为什么您需要再次遍历它的原因。

希望这会有所帮助!

答案 1 :(得分:0)

内置的regroup标记应允许您执行此操作,但是您需要使用两次以实现所需的嵌套分组。

{% regroup game by location as games_loc %}  <!-- Group by "location" -->
{% for location, l_games in games_loc %}
    <div>{{ location }}</div>

    {% regroup l_games by group as games_grp %}  <!-- Group by "group" -->
    {% for group, g_games in games_grp %}
        <div>{{ group }}</div>

        {% for g in g_games %}  <!-- Display games in group -->
            <div>{{ g }}</div>
        {% endfor %}
    {% endfor %}
{% endfor %}