如何根据它的归属标签

时间:2016-03-07 08:20:46

标签: python django

我有两个模特新闻和类别,而在新闻中我有类别的外键。我知道如何在一个模板中显示具有相同类别的新闻。但是,在我的主页上,我试图显示每个类别的特色新闻。这是我遇到问题的地方。 这是我的models.py

class News(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()
    category = models.ForeignKey("Tag")
    active = models.BooleanField(default=True)
    featured = models.BooleanField(default=False)
    top = models.BooleanField(default=False)
    slug = models.CharField(max_length=255, unique=True)
    featuredInCat = models.BooleanField(default=False)
    objects = StoryManager()



class NewsQueryset(models.query.QuerySet):
    def active(self):
        return self.filter(active=True)
    def featuredInCat(self):
        return self.filter(featuredInCat=True)


class NewsManager(models.Manager):
    def get_queryset(self):
        return NewsQueryset(self.model, using=self._db)
    def get_featuredInCat(self):
        return self.get_queryset().active().featuredInCat()
    def all(self):
        return self.get_queryset().active()


class Category(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(max_length=5000, null=True, blank=True)

在views.py

def category_list(request):
    categoryList = NewsCategory.objects.all()

    featuredInCat = News.objects.get_featuredInCat()
    context = {
        "featuredInCat":featuredInCat
        "categoryList":categoryList,


}
    return render(request,"news/category_list.html", context)

在我的模板中

  {% for category in categoryList %}
<div class='col-sm-4'>
<div id="container">{{category.title}}</h1>
    <ul>
    {% for x in featuredInCat %}
 <a href='{{ x.get_absolute_url }}'><li class="unique">{{x.title}}</li></a>
    {% endfor %}
    </ul>
    </div>  

<hr>
</div>
{% endfor %}

然后在每个类别中显示featuresInCat,其中featuresInCat应仅显示在其“类别”部分中。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

看看django的the built-in regroup template tag。您需要将模板更改为以下内容:

{% regroup featuredInCat by category as news_list %}

<ul>
{% for news in news_list %}
    <li>{{ news.grouper.title }}
    <ul>
        {% for item in news.list %}
          <li>{{ item.title }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

答案 1 :(得分:3)

您可以更改for循环以迭代正确的对象

{% for x in category.news_set.get_featuredInCat %}

您不再需要上下文变量