Working Ninja
2017-08-24T21:01:28
Custom Manager for Django

Here's a custom manager for a class (Change) that gets all approved changes where "today's date" falls between the Change.start_date and Change.end_date.

# models.py
import datetime
...
# Custom Change Manager that only pulls active, approved changes
class ApprovedChanges(models.Manager):
    def get_queryset(self):
        today = datetime.date.today()
        return super(ApprovedChanges, self).get_queryset().filter(
            approved=True,
            start_date__lte=today,
            end_date__gte=today
        )

class Change(models.Model):
    ...
    approved_changes = ApprovedChanges()

In our view, we could then call all changes for "today" that have been approved:

# views.py
def todays_changes(self):
   changes = Changes.approved_changes.all()
   ...

Source: https://docs.djangoproject.com/en/stable/topics/db/managers/