Ana Balica

Hi, I'm Ana.

I'm a software developer. I mostly do Python. This blog is about my adventures with code, travel experiences and relevant life events. I try not to take myself too seriously.

Here's what I'm doing now.

Occasionally I give talks.

Please don't take my words for granted, because Internet is full of bad advice, and I might be part of it inadvertently.

Django week_day Field lookup

Django’s ORM offers built-in field lookups, one of which is week_day. So one can do Sale.objects.get(sale_date__week_day=2) to find out how well is the business doing on Mondays.

Wait what? How come 2 is a Monday? According to Python documentation, there are 2 possible weekday representations (identical methods are available for datetime objects):

Whereas Django interprets the integer as 1 (Sunday) to 7 (Saturday). Here’s a short util to transform from Python to Django weekday value:

def to_django_weekday(date):
    return (date.isoweekday() % 7) + 1

Databases too have different interpretations for this value:

  • MySQL and Oracle are identical to Django’s weekday value - 1 (Sunday) to 7 (Saturday)
  • PostgreSQL - 0 (Sunday) to 6 (Saturday)
  • SQLite is identical to Python’s isoweekday() representation - 1 (Monday) to 7 (Sunday)

Even though the value varies between databases, it’s still not exactly clear why this value is so alien to any of the Python representations. I think I will pester some people today at DjangoCon US.


UPD: Thanks to Marc Tamlyn for confirming that there isn’t any special reason for the choice of weekday interpretation in Django (maybe MySQL). This code was last time updated in 2009 and, at this point, an update would be backwards incompatible.