fromdatetimeimportdatetimefromdjango.dbimportmodelsclassActiveManager(models.Manager):""" This special manager only retrieves active objects (when the current date is between the object's publish date and/or its expiration date). The date fields are given when creating the Manager instance. If either is None then the manager will not take it into account for filtering. Example definition for a model: class ExampleModel(models.Model): publish_date = models.DateTimeField() expire_date = models.DateTimeField(blank=True, null=True) actives = ActiveManager(from_date='publish_date', to_date='expire_date') Or if the model only had an expire_date: class ExampleModel(models.Model): expire_date = models.DateTimeField(blank=True, null=True) actives = ActiveManager(from_date=None, to_date='expire_date') Each instance of the manager has an attribute date_filters which can be used in custom queries. For example, if you have a ManyToMany relationship to a model with ActiveManager and you can't access via the manager (because you need to use select_related, for example) then you can do: instance.many_to_many.filter(*ExampleModel.actives.date_filters) """def__init__(self,from_date=None,to_date=None):super(ActiveManager,self).__init__()self.from_date=from_dateself.to_date=to_datenow=datetime.nowiffrom_dateandto_date:self.date_filters=(models.Q(**{'%s__isnull'%self.to_date:True})|models.Q(**{'%s__gte'%self.to_date:now}),models.Q(**{'%s__isnull'%self.from_date:True})|models.Q(**{'%s__lte'%self.from_date:now}))eliffrom_date:self.date_filters=(models.Q(**{'%s__isnull'%self.from_date:True})|models.Q(**{'%s__lte'%self.from_date:now}),)elifto_date:self.date_filters=(models.Q(**{'%s__isnull'%self.to_date:True})|models.Q(**{'%s__gte'%self.to_date:now}),)else:raiseValueError,"At least one date field is required"defget_query_set(self):"""Retrieves items with publication dates according to self.date_filters """returnsuper(ActiveManager,self).get_query_set().filter(*self.date_filters)