V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
askask
V2EX  ›  Django

django 按作者展示文章

  •  
  •   askask · 2016-04-08 15:38:28 +08:00 · 3349 次点击
    这是一个创建于 2939 天前的主题,其中的信息可能已经有所发展或是发生改变。

    数据库中存了很多文章。不同的作者写的。

    我想通过 django 在前台展示同一个作者下面的所有文章。 该怎么写了?

    展示效果基本如下:

    作者 1 : 1 、你好 2 、你好 2

    作者 2 : 1 、他好 2 、他好 2

    9 条回复    2016-04-26 09:10:29 +08:00
    virusdefender
        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")
    askask
        2
    askask  
    OP
       2016-04-08 15:57:48 +08:00
    @virusdefender print author.articles.all() 这条命令不行啊。 而且我是要在 template 里面用
    Yasic
        3
    Yasic  
       2016-04-08 16:03:34 +08:00
    在 view 里面把 author 当做参数通过 render 传给 template , template 进行渲染。
    参考 Django Book 第四章和第九章
    zmj1316
        4
    zmj1316  
       2016-04-08 16:04:55 +08:00
    先从数据库读进来给模板去渲染?
    模板里面写
    {% for a in author.articles %}
    ...a.title a.text...
    {% endfor %}
    大概这样?
    askask
        6
    askask  
    OP
       2016-04-08 16:28:36 +08:00
    virusdefender
        7
    virusdefender  
       2016-04-08 16:42:06 +08:00
    @askask 这只是一个 demo 啊,你把 print 的结果传到 template 里面去循环不就行了
    saber000
        8
    saber000  
       2016-04-09 09:45:04 +08:00   ❤️ 1
    askask
        9
    askask  
    OP
       2016-04-26 09:10:29 +08:00
    @saber000 已感谢!亲测可用。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4474 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:09 · PVG 18:09 · LAX 03:09 · JFK 06:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.