How to filter a queryset based on the result of a method on the model class that returns a boolean?

心不动则不痛 提交于 2019-12-08 03:45:31

问题


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?

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

回答1:


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



来源:https://stackoverflow.com/questions/27652223/how-to-filter-a-queryset-based-on-the-result-of-a-method-on-the-model-class-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!