Sunday snippets are bits of code that I've found useful in past projects. I post them here in hopes that someone else will find them useful. Most of these are Github Gists and you can follow them there too if you want.
Note: This is now a deprecated way of buildling chainable querysets. Django 1.7 has built in support this type of thing now.
I am always writing managers in Django to handle queries more simply. I always forget how to write them so that they can be chained together. This example is the best I have done, with the smallest amount of code. It seems redundant because you have to repeat the manager methods, but returning a query set allows them to be chained together. Enjoy! ``` from django.db.models.query import QuerySet from django.db.models import Manager from datetime import date
class EventQuerySet(QuerySet): def published(self): return self.filter(published=True)
def availableforadding(self): return self.filter(published=True, private=False)
def active(self): return self.filter(eventtimestartdate__gte=date.today())
def datefilter(self, startdate, enddate): return self.filter(eventtimestart_dategte=startdate, eventtimeend_datelte=end_date)
class EventManager(Manager): def getqueryset(self): return EventQuerySet(self.model, using=self._db)
def published(self): return self.getqueryset().published()
def availableforadding(self): return self.getqueryset().availableforadding()
def active(self): return self.getqueryset().active()
def datefilter(self, startdate, enddate): return self.getqueryset().datefilter(startdate, enddate) ```