数据库中存了很多文章。不同的作者写的。
我想通过 django 在前台展示同一个作者下面的所有文章。 该怎么写了?
展示效果基本如下:
作者 1 : 1 、你好 2 、你好 2
作者 2 : 1 、他好 2 、他好 2
![]() | 1 virusdefender 2016-04-08 15:46:26 +08:00 for author in Author.objects.all(): ====print author.articles.all() class Article(models.Model): ====author = models.ForeignKey(Author, related_name="articles") |
2 askask OP @virusdefender print author.articles.all() 这条命令不行啊。 而且我是要在 template 里面用 |
![]() | 3 Yasic 2016-04-08 16:03:34 +08:00 在 view 里面把 author 当做参数通过 render 传给 template , template 进行渲染。 参考 Django Book 第四章和第九章 |
![]() | 4 zmj1316 2016-04-08 16:04:55 +08:00 先从数据库读进来给模板去渲染? 模板里面写 {% for a in author.articles %} ...a.title a.text... {% endfor %} 大概这样? |
5 askask OP |
6 askask OP |
![]() | 7 virusdefender 2016-04-08 16:42:06 +08:00 @askask 这只是一个 demo 啊,你把 print 的结果传到 template 里面去循环不就行了 |
![]() | 8 saber000 2016-04-09 09:45:04 +08:00 ![]() django 模板有 regroup : https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#regroup |