我遇到了这个问题:假设您有一个博客应用程序,并且想要显示创建的所有帖子。但是您的帖子可能是“粘性”或“特色”的,必须首先显示,并且必须驻留在不同的 html“ block ”中。也许这不是最好的例子,但毕竟是我需要的。
所以,模型很简单:
class Post(models.Model):
title = models.CharField()
content = models.TextField()
featured = models.BooleanField(default=False)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
ordering = ['-featured','-created']
在 View 中,我只是查询所有帖子并将其显示在模板中:
def my_view(request):
return render_to_response('template.html',{'posts':Post.objects.all()})
现在,问题出在我的模板中,我想要的结果是:
<html>
<div class='featured-posts'>
<ul>
<li> A Featured post</li>
</ul>
</div>
<div class='not-featured-posts'>
<ul>
<li> A NON Featured post</li>
</ul>
</div>
</html>
我能做什么?我在想也许我可以捕获那些分开的人,这样:
return render_to_response('template.html',{
'featured':Post.objects.filter(featured=True),
'non_featured':Post.objects.filter(featured=False)
})
但我真的不喜欢这种方法,有没有“基于模板”的解决方案?
谢谢!
最佳答案
Regroup在特色
字段上。
关于python - Django:标签中的For循环显示不同的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9780119/