这是我的观点.py
def following(request):
currentUser = User.objects.get(pk=request.user.id)
currentUser_followings = Following_System.objects.get(user=currentUser).following
allPosts = Post.objects.all().order_by("-timestamp").reverse()
followingPosts = []
for user in currentUser_followings.all():
for post in allPosts:
if post.author == user:
followingPosts.append(post)
**post_likers_ids = {post.id: list(post.likers.values_list('id', flat=True)) for post in followingPosts}**
# Show 10 posts per page.
paginator = Paginator(followingPosts, 5)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, "network/following.html",{
"page_obj": page_obj,
"post_likers_ids" : post_likers_ids
})
我调试,post_likers_ids 返回:({4: [2], 2: [1,3,5]}) 现在在我的以下 html 中,为什么 if 条件总是 false (尽管对于某些人来说应该是 true,因为我知道预期的输入输出):
{% for post in page_obj %}
<div class="list-group-item">
{% with post_id=post.id %}
{% if user.id in post_likers_ids.post_id %}
<p>The user liked this </p>
{% else %}
<p>The user have not liked this </p>
{% endif %}
{% endwith %}
</div>
{% endfor %}
这是我的模型,如果有帮助的话:
class Post(models.Model):
content = models.TextField(blank=False)
author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author")
timestamp = models.DateTimeField(auto_now_add=True)
likers = models.ManyToManyField("User", related_name="liked_posts", blank=True)
def serialize(self):
likes_count = self.likers.count() #
likers = [user.id for user in self.likers.all()]
return {
"id": self.id,
"content": self.content,
"author": self.author.username,
"author_id": self.author.id,
"timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"),
"likes": likes_count,
"likers" : likers,
}
好像用的是jinja模板,
post_likers_ids.post_id
行为怪异,例如,当 post_id = 4 时;使用
post_likers_ids.4
返回正确的值,但使用 post_likers_ids.post_id 返回空
您可能会通过以下方式检查:
{% if user.id in post_likers_ids[post_id] %}
<!-- … -->
{% endif %}
但是构建这样的字典本身效率不高,因为它会触发n查询n帖子。