我建议你换一下
related_name
你的属性
Like
模型,甚至可以删除它以使用默认名称:
class Like(models.Model):
liker = models.ForeignKey(User)
photo = models.ForeignKey(Photo)
liked = models.BooleanField()
现在您可以这样使用它:
all_likes_of_a_user = user_instance.like_set.all()
all_likes_of_a_photo = photo_instance.like_set.all()
现在,要迭代视图中的照片,可以使用:
for photo in Photo.objects.all():
like_count = photo.like_set.count()
has_liked = photo.like_set.filter(liker=request.user).exists()
为了在模板中使用它,可以添加一个嵌套循环:
{% for photo in Photo.objects.all %}
Like count: {{ photo.like_set.count }}
Has this user liked this photo:
{% for like in photo.like_set.all %}
{% if like.liker == user %}
yes
{% endif %}
{% endfor %}
{% endfor %}
或向您的
Photo
模型:
class Photo(models.Model):
...
def users_that_liked_it(self):
return [
e.liker.pk
for e in self.like_set.all()]
{% for photo in Photo.objects.all %}
Like count: {{ photo.like_set.count }}
Has this user liked this photo:
{% if user.pk in photo.users_that_liked_it %}
yes
{% else %}
no
{% endif %}
{% endfor %}