亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取對象和多對多對象信息

如何獲取對象和多對多對象信息

LEATH 2021-08-14 16:08:01
我想獲取信息:如果請求用戶對該項目進行投票。我的項目類: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')
查看完整描述

2 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

我解決了這個問題。

queryset = queryset.annotate(user_vote=Count("votes__user_id", filter=Q(votes__id=filters['user_id'])))

我不知道 votes__id 在這種關系中等同于用戶 ID


查看完整回答
反對 回復 2021-08-14
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

嘗試在投票字段上使用相關名稱:


votes = models.ManyToManyField(User, related_name='projects') 這樣你就可以訪問用戶通過這個投票的所有項目 related_name


user = User.objects.filter(username='john')

user.projects.all() # > all projects that user voted for


查看完整回答
反對 回復 2021-08-14
  • 2 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號