Django-manytomoly过滤器,带中间模块

2024-05-20 22:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下型号:

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

在我看来,当前登录的用户通过

^{pr2}$

我要检索p_user的所有关系,这些关系属于PersonneEnums.RELATION_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
)

有人能解释一下为什么这不起作用吗?在


Tags: namesrcfriendmodelstypeclassbasemodelrelated
1条回答
网友
1楼 · 发布于 2024-05-20 22:04:07

在这两种情况下,您都尝试使用默认管理器objects,而您需要使用关系管理器。然而,由于关系是不明确的,因此似乎会有一个问题,即,当像这样查询关系时:

p_user.relations.filter(type_relation=PersonneEnums.RELATION_AMI)

Django无法决定是否应该在此查询中使用src还是{}。在

以下查询应该有效:

^{pr2}$

同样,类似这样的方法可能会起作用(参见^{}的说明):

p_user.relations.filter(relation_src__type_relation=PersonneEnums.RELATION_AMI
               ).filter(relation_dst__type_relation=PersonneEnums.RELATION_AMI)

相关问题 更多 >