Creating a Custom Manager for a MongoEngine Document in Django
This is just a quick how-to on creating a custom manager for a MongoEngine Model in Django, similar to how you would normally create a Manager for a Model in Django. Usually in Django with a PostgreSQL or MySQL database, one would do this:
class PollManager(models.Manager): def with_counts(self): ... class OpinionPoll(models.Model): question = models.CharField(max_length=200) poll_date = models.DateField() objects = PollManager()
Now, when we are using Mongoengine Documents, it works only slightly differently, and you just need to know how (since this doesn't seem to be documented anywhere). This is how I do it:
from mongoengine import *
from mongoengine.queryset import QuerySet
class PollManager(QuerySet):
def __init__(self, document, collection, *args, **kwargs)
super(PollManager, self).__init__(document, collection, *args, **kwargs)
def with_counts(self):
...
class OpinionPoll(Document):
question = StringField(max_length=200)
poll_date = DateTimeField()
OpinionPoll.add_to_class('objects', PollManager(OpinionPoll,
OpinionPoll.objects._collection))
You might notice that the last line contains what developers often refer to as "monkey patching", adding something to a class after it was defined. In this case, however, it is a necessary evil, since we need to be able to access the OpinionPoll class to instantiate the manager. Maybe there's a better way, and if so I'll be happy to hear about it. Left as an exercise for the reader, as they say!
If you found this post interesting, you might also like our blog post, Introducing Jade for Templates in Django and Flask
