首页 > 解决方案 > 如何访问 Django ManyToMany Field 的数据?

问题描述

我想在我的社交媒体网站的主页中创建点赞功能。我正在使用 ManyToManyField 在特定帖子上存储喜欢,如 models.py 中所示。在我的主页中,我有帖子列表,我想检查当前登录用户是否已喜欢的帖子的天气。

在我的views.py中,我正在使用

post = Posts.objects.filter('likes')
if post.likes.filter(id=request.user.id).exists():

模型.py

class Posts(models.Model):
title = models.CharField(max_length=250, blank=False)
content = models.CharField(max_length=15000,
                           help_text="Write Your thought here...")
likes = models.ManyToManyField(User, blank=True)

视图.py

def home(request):
post = Posts.objects.filter('likes')
print('Thats just Test', post)
if post.likes.filter(id=request.user.id).exists():
    print("Already Exixts")
    is_liked = False
context = {
    'all_posts': all_posts,
    'is_liked': is_liked,
}
return HttpResponse(template.render(context, request))

hometemplte.html:(仅喜欢按钮)

<form action="{% url 'like_post' %}" method="POST">
            {% csrf_token %}
            {% if is_liked %}
              <button type="submit" name="like" value="{{ post.id }}" class="btn upvote liked">Liked</button>
            {% else %}
              <button type="submit" name="like" value="{{ post.id }}" class="btn upvote">Upvote</button>
            {% endif %}
          </form>    

标签: pythondjango

解决方案


如果要获取ManyToMany字段的数据,对于向后映射,您需要related_name在声明模型时使用参数。

所以你的属性将是:

likes = models.ManyToManyField(User, blank=True, related_name='likes')

您检查特定帖子是否已被用户喜欢的查询是:

post.likes.filter(id=request.user.id).exists():

更新

您的问题是您在一行中检索多个帖子:

Posts.objects.filter('likes'),它返回一个查询集。您需要获取特定的帖子,然后检查用户是否喜欢该帖子。

post = Posts.objects.all()[0]不会抛出任何错误。


推荐阅读