sasklacz
sasklacz

Reputation: 3638

Django Managers

I have the following models code :

from django.db import models
from categories.models import Category

class MusicManager(models.Manager):
    def get_query_set(self):
        return super(MusicManager, self).get_query_set().filter(category='Music')
    def count_music(self):
        return self.all().count()

class SportManager(models.Manager):
    def get_query_set(self):
        return super(MusicManager, self).get_query_set().filter(category='Sport')        

class Event(models.Model): 
    title = models.CharField(max_length=120)
    category = models.ForeignKey(Category)
    objects = models.Manager()
    music = MusicManager()
    sport = SportManager()

Now by registering MusicManager() and SportManager() I am able to call Event.music.all() and Event.sport.all() queries. But how can I create Event.music.count() ? Should I call self.all() in count_music() function of MusicManager to query only on elements with 'Music' category or do I still need to filter through them in search for category first ?

Upvotes: 1

Views: 1078

Answers (2)

Chris Lawlor
Chris Lawlor

Reputation: 48982

You can think of a manager as a 'starting point' for a query - you can continue to chain filters just as if you'd started out with the default manager.

For example, Event.objects.filter(category='Music').filter(title='Beatles Concert') is functionally equivalent to Event.music.filter(title='Beatles Concert')

So, as Daniel says, you don't really need to do anything special, just choose one of your custom managers instead of objects and go from there.

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 600049

You don't need to do anything (and your count_music method is unnecessary). The count() method will use the existing query as defined by get_query_set.

Upvotes: 2

Related Questions