为查询集合并两个模型管理器

时间:2011-07-24 00:08:23

标签: django django-models

有没有办法将自定义模型管理器应用于默认模型管理器生成的QuerySet?

我需要使用默认的模型管理器来过滤QuerySet,因为我有一个M2M直通模型,并且最容易在那里进行过滤,而不是将自定义管理器的复杂性提高一个数量级:此过滤器看起来如下:

talent_set = UserProfile.objects.filter(positions=Position.objects.get(position=filter))

然后我需要将自定义模型管理器应用于此过滤查询,如下所示:

final_talent_set = UserProfile[filtered].custom_manager.do_something()

有没有办法做到这一点,或者我应采取不同的方法?也许是一种将列(从自定义管理器)附加到默认管理器末尾的方法?谢谢。

1 个答案:

答案 0 :(得分:5)

嗯,为什么不在filter中使用相同的get_query_set()

我的意思是:

class MyManager(models.Manager):
    def get_query_set(self):
        return super(MyManager, self).get_query_set().filter(
            positions=Position.objects.get(position=filter)
        )

    def do_something(self):
        q = self.get_query_set()
        # do something