开发者

Multiple ModelManager filter methods

开发者 https://www.devze.com 2023-01-21 12:20 出处:网络
def by_this(self): return super(MyModelManager, self).get_query_set().filter(this=True) def by_that(self):
def by_this(self):
        return super(MyModelManager, self).get_query_set().filter(this=True)

def by_that(self):
        return super(MyModelManager, self).get_query_set().filter(that=True)
开发者_C百科

If i do MyModel.objects.by_this() or by_that() it works.

But i want to do: MyModel.objects.by_this().by_that()


As others say, you need custom QuerySet. Here are some examples of how to do this:

http://djangosnippets.org/snippets/562/
http://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/index.html


MyModel.objects will return your ModelManager type, but by_this returns a queryset. So you can't call by_that on the returned object and the chaining doesn't work. You could do: MyModel.objects.by_this().filter(that=True). Or just define a by_this_and_that method in your ModelManager derived class.


As ars says, your methods return a queryset. So what you need to do is to create a custom subclass of QuerySet, which contains the by_this and by_that methods, and then in MyModelManager.get_query_set return your subclassed queryset.

0

精彩评论

暂无评论...
验证码 换一张
取 消