首页 > 解决方案 > 如何获取对象和多对多对象信息

问题描述

我想获取信息:如果请求用户对此项目投票。

我的项目类:

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')

标签: pythondjango

解决方案


尝试在投票字段上使用相关名称:

votes = models.ManyToManyField(User, related_name='projects') 这样您就可以访问用户为此投票的所有项目related_name

user = User.objects.filter(username='john')
user.projects.all() # > all projects that user voted for

推荐阅读