我想获取信息:如果请求用户对此项目进行投票。
我的项目班级:
class Project(TimestampedModel):
title = models.CharField(max_length=120)
description = models.TextField()
company = models.ForeignKey(
Company, on_delete=models.CASCADE
)
tags = models.ManyToManyField(Tag)
votes = models.ManyToManyField(User)
我的查询,我尝试通过内部注释和过滤来获取它,但不起作用
queryset = Project.objects.all()
if 'title' in filters.keys() and filters['title'] is not None:
queryset = queryset.filter(title__icontains=filters['title'])
queryset = queryset.annotate(num_votes=Count("votes"))
queryset = queryset.annotate(user_vote=Count("votes__user_id", filter=Q(votes__user_id=filters['user_id'])))
queryset = queryset.order_by('-created_at')
答案 0 :(得分:0)
我解决了这个问题。
queryset = queryset.annotate(user_vote = Count(“ votes__user_id”,filter = Q(votes__id = filters ['user_id'])))
在这种关系中,我不知道voice__id等同于用户ID
答案 1 :(得分:0)
尝试在投票字段中使用相关名称:
votes = models.ManyToManyField(User, related_name='projects')
这样,您可以访问用户为此related_name
user = User.objects.filter(username='john')
user.projects.all() # > all projects that user voted for