我正在尝试从用户关注的所有组中获取发布对象。我能够获得用户遵循的组列表以及所有帖子的查询集,但是我很难将对象传递到模板。
我的模特:
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT)
title = models.CharField(max_length = 120, default = '', blank = False)
body = models.TextField()
class Community(models.Model):
title = models.CharField(max_length = 50, default = '', unique = True)
followers = models.ManyToManyField(Account, related_name = "community_followers")
posts = models.ManyToManyField(Post, blank = True, related_name = "community_posts")
def __str__(self):
return self.title
class Account(AbstractBaseUser):
username = models.CharField(max_length = 30, unique = True)
email = models.EmailField(verbose_name = "email", max_length = 50, unique = True)
date_joined = models.DateTimeField(verbose_name = "date joined", auto_now_add = True)
last_login = models.DateTimeField(verbose_name = "last login", auto_now = True)
is_admin = models.BooleanField(default = False)
is_active = models.BooleanField(default = True)
is_staff = models.BooleanField(default = False)
is_superuser = models.BooleanField(default = False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
视图:
user = request.user
user_communities = user.community_followers.all()
queries = []
for community in user_communities:
queries.append(community.posts.all())
context['posts'] = queries
return render(request, "home/index.html", context)
模板:
{% for post in posts %}
{{ post.title }}
<hr>
{% endfor %}
所有帖子均未显示在模板中,我似乎也无法对其进行排序。我认为我的实现中肯定有问题。
答案 0 :(得分:0)
假设帐户是AUTH_USER_MODEL,则可以在一个查询中执行此操作:
Post.objects.filter(community_posts__followers=request.user)
(如果没有,请发布帐户模型。)