Django:查询多个外键

4
首先,我相信这是一个简单的问题。我刚开始学习Django,像所有初学者一样,我想建立一个简单的博客。
我有一个简单的数据模型,一个帖子模型,它包含通过FK链接到用户的链接。
models.py
class Post(TimeStampedActivate):
    """
    A blog post
    """
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    excerpt = models.TextField(blank=True)
    body = models.TextField()
    publish_at = models.DateTimeField(default=datetime.datetime.now())
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False, help_text='Is the blog post active?')
    user = models.ForeignKey(User, related_name='post_user')

    def __unicode__(self):
        return self.title

我想要一个页面,列出所有帖子以及创建帖子的人的用户名。我的当前视图如下所示:
views.py
def index(request):
    posts = Post.objects.filter(active=True)   
    user = User.objects.get(id=1)
    return render(request, 'blog/index.html', {'posts': posts, 'user': user})

我的模板 目前,它只显示与 ID 为 1 的用户名称相匹配的内容。
{% for post in posts %}
    <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p>{{ post.excerpt|truncatewords:30 }}</p>
    <p>Posted by {{ user.first_name }} {{ user.last_name }}</p>
{% endfor %}

我应该如何修改我的views.py文件来确保我获取发布帖子的用户的名字和姓氏?
2个回答

3

视图:

def index(request):
    posts = Post.objects.filter(active=True)   
    return render(request, 'blog/index.html', {'posts': posts})

模板:

{% for post in posts %}
    <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p>{{ post.excerpt|truncatewords:30 }}</p>
    <p>Posted by {{ post.user.first_name }} {{ post.user.last_name }}</p>
{% endfor %}

非常感谢你,Alp!我过度思考了。我想象着使用 for 循环和各种疯狂的巫术。 - Kristian Roebuck
不客气。我也是 Django 的新手,上周才开始学习。如果你感兴趣的话,可以看看我的当前(未回答)问题 :) - Alp
我会浏览一下你的问题,看看能否提供帮助。 :) - Kristian Roebuck
1
除了这个答案之外,还要查看select_related以防止每个帖子获取用户表信息时进行额外的数据库查询。 - Yuji 'Tomita' Tomita

1

他将user分配为具有pk = 1的User。此外,request.user不是已登录的用户吗? - ch3ka
在模板中,“request.user”和“user”是等价的。 - Alp
如果您使用了 RequestContext 并将 auth 添加到 TEMPLATE_CONTEXT_PROCESSORS 中,那么 user 就等于 request.user。https://docs.djangoproject.com/en/dev/topics/auth/#authentication-data-in-templates我之前很困惑,因为我不知道 user 始终是可用的。 - dannyroa
ch3ka:是的。你对我的回答进行了负评吗?我不会感到冒犯。我的回答基本上与正确答案相同。 - dannyroa
抱歉,您的回答似乎指向了错误的方向。能否在回答中澄清一下?我会取消踩的。 - ch3ka
我刚刚添加了一个关于为什么用户与请求用户相同的解释。 - dannyroa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接