user764357
user764357

Reputation:

Django day and month event date query

I have a django model that looks like this:

class Event(models.Model):
    name = model.CharField(...etc...)
    date = model.DateField(...etc...)

What I need is a way to get all events that are on a given day and month - much like an "on this day" page.

def on_this_day(self,day,month):
    reutrn Events.filter(????)

I've tried all the regular date query types, but they all seem to require a year, and short of iterating through all years, I can't see how this could be done.

Upvotes: 3

Views: 781

Answers (1)

bakkal
bakkal

Reputation: 55448

You can make a query like this by specifying the day and the month:

def on_this_day(day, month):
    return Event.objects.filter(date__day=day, date__month=month)

It most likely scans your database table using SQL operators like MONTH(date) and DAY(date) or some lookup equivalent

You might get a better query performance if you add and index Event.day and Event.month (if Event.date is internally stored as an int in the DB, it makes it less adapted to your (day, month) queries)

Here's some docs from Django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#month

Upvotes: 4

Related Questions