简体   繁体   English

如何在Django中获得用户的所有帖子?

[英]how to get all posts User by User in Django?

I have a simple blog app and I want to show "all posts" submitted by users in blocks in my home page. 我有一个简单的博客应用程序,我想在我的主页中显示用户在块中提交的“所有帖子”。 I mean i want to have each users posts in block section. 我的意思是我想让每个用户在块部分发帖。 my model is like this: 我的模型是这样的:

'''
    class Post(models.Model):
        title = models.CharField(max_length=120)
        description = models.CharField(max_length=250)
        author = models.ForeignKey(settings.AUTH_USER_MODEL,default=1, 
        on_delete=models.CASCADE)
'''

I expect that loop through all users and all of the posts created by them and show them in my home page, but i cant get them USER by USER. 我希望循环遍历所有用户和他们创建的所有帖子并在我的主页中显示它们,但我不能通过USER获取它们。 Please take a look at this picture So how should i write my model or query the database to get desired result has shown above? 请看一下这张图片那么我应该如何编写我的模型或查询数据库以获得所需的结果? Thanks in advance 提前致谢

Build an object and pass it to the template. 构建一个对象并将其传递给模板。

users = Users.objects.all()
nested_posts = {}
for user in users:
    posts = user.post_set
    nested_posts[user] = posts

Then, in your template: 然后,在您的模板中:

{% for user, posts in nested_posts %}
Posts for the user "{{user}}":
{% for post in posts %}
Post:{{post.id}}, Body:{{post.body}}, Date:{{post.date}}
{% endfor %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM