如何将 ManyToManyField 与另一个 ManyToManyField 进行比较
我有一个 Partner
模型
class Partner(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
group = models.OneToOneField(
Group, on_delete=models.DO_NOTHING, blank=True, null=True)
def __str__(self):
return self.name
我还有另外 2 个模型,一个是 CustomUser,另一个是 Quote
class CustomUser(AbstractUser):
#...
name = models.CharField(max_length=160, null=True, blank=True)
partner = models.ManyToManyField(
Partner, blank=True)
class Quote(models.Model):
#...
visibility = models.CharField(max_length=10)
partner = models.ManyToManyField(
Partner, blank=True)
两个模型都有一个与 ManyToManyField 相关的合作伙伴字段到合作伙伴模型
现在我想在以下视图中比较它们: 合作伙伴字段可以有多个合作伙伴,例如合作伙伴1、合作伙伴2、合作伙伴3
如何在 Quote 和 CustomUser 模型中查找彼此匹配的合作伙伴
可以说,其中一个 Quote 对象在 ManyToManyField 中具有一组 [partner1 和 Partner6],而我仅希望在其合作伙伴 ManyToManyField 集中也有partner1 和partner6 的用户能够访问该报价。
那么我该如何过滤和比较它们呢? 我还阅读了文档,但无法重现该解决方案。帮助将不胜感激。
编辑:我可以解释一下,可以说,从报价中的整套合作伙伴中,如果甚至一个合作伙伴与 CustomUser 的一组合作伙伴相匹配,那么 CustomUser 也应该有权访问它。
I have a model of Partner
class Partner(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
group = models.OneToOneField(
Group, on_delete=models.DO_NOTHING, blank=True, null=True)
def __str__(self):
return self.name
I have 2 other models one is CustomUser and other is Quote
class CustomUser(AbstractUser):
#...
name = models.CharField(max_length=160, null=True, blank=True)
partner = models.ManyToManyField(
Partner, blank=True)
class Quote(models.Model):
#...
visibility = models.CharField(max_length=10)
partner = models.ManyToManyField(
Partner, blank=True)
Both have a partner field related with ManyToManyField to Partner Model
Now I want to compare them in the views like:
partner field can have multiple partners like partner1, partner2, partner3
how to to find the partners matching to each other inside the Quote and CustomUser model
Lets say, One of the Quote object have set of [partner1 and partner6] in the ManyToManyField and I only want to have access to that quote to users who also have partner1 and partner6 in their partner ManyToManyField set.
So how can I filter and compare them ?
I also read the docs but didn't able to reproduce the solution. help would be appreciated.
Edit : I can explain it a little , lets say From whole set of partner's in the quote if even one partner is matched to set of partners to the CustomUser then CustomUser should also have access to it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以
.filter(...)
[Django-doc]
with:
这将返回一个包含
Quote
的QuerySet
,其中包含至少一位与my_user
共同的合作伙伴
。由于存在共同的
合作伙伴
,因此会多次返回相同的报价
。您可以使用.distinct()
[Django-doc]
以避免这种情况:
You can
.filter(…)
[Django-doc] with:This will return a
QuerySet
ofQuote
s that have at least onePartner
in common withmy_user
.The same
Quote
will be returned that many times as there arePartner
s in common. You can use.distinct()
[Django-doc] to avoid that: