python - 如何获取对象和多对多对象信息
问题描述
我想获取信息:如果请求用户对此项目投票。
我的项目类:
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')
解决方案
尝试在投票字段上使用相关名称:
votes = models.ManyToManyField(User, related_name='projects')
这样您就可以访问用户为此投票的所有项目related_name
user = User.objects.filter(username='john')
user.projects.all() # > all projects that user voted for
推荐阅读
- c# - 使用 Id 属性插入具有多对多的未跟踪实体
- wpf - WPF 单选按钮属性绑定
- r - 连接列表的值以在 r 中创建 .csv 文件
- r - 在 R 中计算多行买卖的回报
- google-bigquery - IN 可以通过使用 struct 构造函数语法与多部分键一起使用吗?
- laravel - NotFoundHttpException 未在 Lumen 5.6 的控制器中捕获
- python - python aiohttp-sse 恰好在 6 个请求后超时
- java - 通过 BLE 向 MCU 发送字节数组
- xml - jaxb2 SAXParseException:发现无效内容
- node.js - Realm.io 未在 macos 上设置