Python 中间型Django-Manytomy滤波器
我有以下型号:Python 中间型Django-Manytomy滤波器,python,django,django-models,django-orm,Python,Django,Django Models,Django Orm,我有以下型号: class Personne(BaseModel): user = models.OneToOneField(User) relations = models.ManyToManyField('self', through='PersonneRelation', symmetrical=False, relat
class Personne(BaseModel):
user = models.OneToOneField(User)
relations = models.ManyToManyField('self', through='PersonneRelation',
symmetrical=False,
related_name='personne_relations')
class PersonneRelation(BaseModel):
type_relation = models.IntegerField(
choices=[(a, b) for a, b in list(PersonneEnums.TAB_RELATIONS.items())],
default=PersonneEnums.RELATION_FRIEND)
src = models.ForeignKey('Personne', related_name='relation_src')
dst = models.ForeignKey('Personne', related_name='relation_dst')
在我看来,我有当前登录的用户通过
p_user = Personne.objects.get(user=view.request.user)
我想检索p\u user
类型为personenums.relationship\u FRIEND
我尝试了很多方法,包括以下代码,但都不起作用:
不起作用:
p_user.objects.filter(relations__type_relation__exact=PersonneEnums.RELATION_AMI)
不起作用:
Personne.objects.filter(
pk=p_user.pk,
relations__type_relation__exact=PersonneEnums.RELATION_AMI
)
有人能给我解释一下为什么这不起作用吗?在这两种情况下,您都试图使用默认的管理器
对象,而您需要使用关系管理器。然而,似乎会有一个问题,因为关系是不明确的,即当查询这样的关系时:
p_user.relations.filter(type_relation=PersonneEnums.RELATION_AMI)
Django无法决定在此查询中是使用src
还是dst
以下查询应该可以工作:
PersonneRelations.objects.filter(
Q(type_relation=PersonneEnums.RELATION_AMI), Q(src=p_user) | Q(dst=p_user))
此外,类似的方法可能会起作用(请参见以下说明):
“不起作用”是什么意思?错误?无效结果?如果我尝试您的解决方案,会出现以下错误:无法将关键字“type\u relation”解析到字段中。选择是:…(模型**Personne**的所有属性列表)
如果我尝试p\u user.relations.filter(relations\uuu type\u relationship=personEnums.relationship\u AMI)
I get:TypeError at/xx相关字段获得无效查找:type\u relationship
@OliverPons,请查看上次答案更新,我必须做几次编辑,但这应该可以。好的,非常感谢你,我几乎在你写答案的时候发现了:我使用了personelations.objects.filter()
东西,但是我的查询要复杂得多,因为src
可以是p_用户
,但是dst
也可以是p_用户
(=如果当前用户邀请了某人或正在被邀请),因此我必须(1)执行一个查询以提取所有src
关系(2)另一个查询以提取所有dst
关系,(2)加入两个查询,只保留Personne
结果,这些结果是relationship\u AMI
。如此复杂的查询..很难向我的客户解释复杂性
p_user.relations.filter(relation_src__type_relation=PersonneEnums.RELATION_AMI
).filter(relation_dst__type_relation=PersonneEnums.RELATION_AMI)