tags:

views:

49

answers:

2

I am trying a simple custom manager, but I can't concatenate custom queries:

class MyManager(models.Manager):    
def some_filter(self):        
    qs = self.get_query_set()
    return qs.filter(score__gt = 10).order_by("-score")
class Game(models.Model):    
     score = models.IntegerField(blank=True, default=0)
     objects = MyManager()


games = Game.objects.filter(any_filter).some_filter()[:5]

But I get QuerySet' object has no attribute 'some_filter'

Edit: It appears that the question is how to concatenate custom filter functions together: seomthing like games = Game.objects.some_filter1().some_filter2()[:5] just won't work for me.

+3  A: 

You can apply some_filter() to MyManager object before QuerySet method filter()

games = Game.objects.some_filter().filter(any_filter)[:5]

Otherwise you should add some_filter method to QuerySet

San4ez
Yes but that doesn't solve the problem if I have 2 filters defined in MyManager: Game.objects.some_filter().some_filter2() won't work
bugspy.net
A: 

I found a way to do it. A new QuerySet class need to be defined too

class GameQS(QuerySet):
    def some_filter1(self):
        return self.filter(score__gt = 10).order_by("-score")
    def some_filter2(self):
        return self.filter(score__gt = 50).order_by("-score")



class GameManager(models.Manager):
    def get_query_set(self):
        return GameQS(self.model, using=self._db)

    def some_filer1(self):
        return self.get_query_set().some_filter1()

    def some_filter2(self):
        return self.get_query_set().some_filter2()
bugspy.net