python - 如何访问 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>
解决方案
如果要获取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]
不会抛出任何错误。
推荐阅读
- python - 如何水平而不是垂直打印多个 ASCII 艺术图形?
- node.js - 如何在运行 Nest js 应用程序时读取进程环境变量?
- oracle - 存储过程异常:ORA-06502:PL/SQL:数字或值错误:字符串缓冲区太小
- r - 与对角权重矩阵一起使用时的焦点最小值问题
- java - 在响应 json 文件中排除数据成员
- r - 使用 if 语句添加列
- python - 交换字母位置
- r - R自动将数据框中缺少的行添加到现有数据框中
- javascript - 使用 google 脚本向 slack 中的几个人发送 dm
- ios - TabView Item 首先在 ipad 上不显示 View 项目