Search code examples
djangodjango-modelsdjango-managers

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 ?


Solution

  • 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.