views:

33

answers:

2

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 ?

+1  A: 

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.

Daniel Roseman
cont() is just an example. Let's say filter_city('City') or anything else. I'm just wondering if in this custom manager if i want to create function for even more specific query, can I use .all() or nothing at all or do I need to filter category once again ?
owca
A: 

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.

Chris Lawlor