我想要做的是在django模板中使用filter(),如下所示:
models.py
from django.db import models
From Django. utils import Timezone
class Category(models.Model):
url = models.CharField(max_length=200)
site_name = models.CharField(max_length=50)
board_name = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField(blank=True)
category = models.ForeignKey(Category)
created_date = models.DateField(blank=True, null=True)
crawl_date = models.DateTimeField()
num_of_comments = models.PositiveSmallIntegerField(default=0, blank=True, null=True)
notice = models.BooleanField(default=False)
views.py
def post_list(request, site_name=None, page=1):
categories = Category.objects.filter(site_name=site_name.upper()).order_by('board_name')
return render(request, 'SNU/post_list.html', {'site_name':site_name.upper(), 'categories':categories})
post_list.html
{% for category in categories %}
<p> {{category}} </p>
{% for post in category.post_set.filter(notice=True) %}
<li>{{ post.title }}</li>
{% endfor %}
{% endfor %}
在post_list.html中,{% for post in category.post_set.filter(notice=True) %}
出现错误。只有category.post_set.all
是我可以在模板中使用的那个?
答案 0 :(得分:0)
您可以在视图级别
执行此操作def post_list(request, site_name=None, page=1):
categories = Category.objects.filter(site_name=site_name.upper(),
notice=True).order_by('board_name')
return render(request, 'SNU/post_list.html',{'site_name':site_name.upper(),
'categories':categories})
如果由于某种原因您需要所有类别,而不仅仅是那些通知= True, 添加一个查询而不通知=在过滤器中为True并将其传递到字典中。
或者,您可以创建自定义标记并提供过滤器 - 请参阅https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/