Django模板过滤

时间:2014-01-24 21:04:04

标签: python html django twitter-bootstrap

我正在尝试创建一个网站,您可以在其中查看不同的“排名”及其中的人员。我已经得到它在自己的可折叠面板中创建排名,因为我正在使用Bootstrap 3,但我无法列出具有该排名的用户。请帮忙。

#team.html template
<div class="container">
 <div class="col-md-2">
  <div class="panel-group" id="accordion">
    {% for rank in Rank_list %}
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{rank.rank_num}}">
            {{ rank.rank_name }}s
          </a>
        </h4>
      </div>
      <div id="collapse{{rank.rank_num}}" class="panel-collapse collapse in">
        <div class="panel-body">
          {% for name in User_list %}
            <li>
              <p>{{name}}</p>
              </li>
          {% endfor %}
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div>

#views.py
class team(generic.ListView):
 template_name = 'main/team.html'
 context_object_name = 'Rank_list'
 context_object_name2 = 'User_list'

 def get_queryset(self):
    return Rank.objects.order_by('rank_num')
 def get_queryset2(self):
    return User.objects.order_by('name')

#models.py
class Rank(models.Model):
    rank_name = models.CharField(max_length=200)
    rank_num = models.IntegerField(default=0)
    def __str__(self):              # __unicode__ on Python 2
        return self.rank_name

class User(models.Model):
    rank = models.ForeignKey(Rank)
    name = models.CharField(max_length=200)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

2 个答案:

答案 0 :(得分:1)

您需要在外键中添加related_name。像这样:

rank = models.ForeignKey(Rank, related_name='users')

然后可以像这样循环访问用户:

{% for user in rank.users.all %}
   {{ user }}
{% endfor %}

答案 1 :(得分:0)

对于每个Rank对象,您可以撤消关系并获取与Users相关的所有Rank

# models.py
# - Use `related_name` for making relationship that are easy to read and follow
# - https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
class User(...):
    rank = models.ForeignKey(Rank, related_name="users")  

# view.py
# - Use prefetch_related allows us to cut down our queries when iterating as we do an up-front join
# - https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
...
def get_queryset(self):
    return Rank.objects.prefetch_related('users')('rank_num')  

# template.py
{% for rank in Rank_List %} # You shouldn't capitalise your template variables
    {% for user in rank.users.all %}  
        {{ user }}
    {% endfor %}
{% endfor %}

最后,您应该使用built-in User model that django's auth module provides