如何根据模型类上返回布尔值的方法的结果来过滤查询集?

Jim*_*Jim 5 python django django-orm

作为我的模型类之一的成员函数,我有一个is_visible(self, user)返回布尔值的方法。根据定义,它将请求用户(DjangoUser模型)作为输入。

我希望能够根据对此方法的响应来过滤查询集。如何使用此函数作为查询集过滤器?

对于上下文,这是我的is_visible实现:

    def is_visible(self, user):
        if self.status.status_internal == "open":
            return True
        if self.owner == user:
            return true

        participations = Participation.objects.filter(event__id=self.id, participant__id=user.id)
        if len(participations) > 0:
            return True

        if self.status.status_internal == "invite":
            return True

        return False
Run Code Online (Sandbox Code Playgroud)

cat*_*ran 4

您不能使用 python 函数来过滤查询集。您必须“复制”此代码并使用Q 对象过滤您的对象。