如何基于返回布尔值的模型类上方法的结果来过滤查询集? [英] How to filter a queryset based on the result of a method on the model class that returns a boolean?

查看:68
本文介绍了如何基于返回布尔值的模型类上方法的结果来过滤查询集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As a member function of one of my model classes, I have an is_visible(self, user) method that returns a boolean. As defined, it takes the requesting user (Django User model) as input.

我希望能够基于对此方法的响应来过滤查询集。

I would like to be able to filter querysets based on the response to this method. How can I use this function as a queryset filter?

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

For context, here is my is_visible implementation:

    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


推荐答案

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

You can't use python function to filter queryset. You have to "duplicate" this code and filter your objects using Q objects.

这篇关于如何基于返回布尔值的模型类上方法的结果来过滤查询集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆