James M.
James M.

Reputation: 11

Django QuerySet Filter by week_day returning nothing

I am currently trying to filter my QuerySet results by the day of the week in Django 2.0.
I can't for the life of me get the django week_day filter datetime__week_day to return any results.

Model

class Session(models.Model):
    def __str__(self):
        return str.join(', ', (str(self.game.name), str(self.datetime_created), str(self.start)))

    game = models.ForeignKey(
        'Game',
        on_delete=models.PROTECT,
        blank=False,
        null=False,
    )

    datetime_created = models.DateTimeField(auto_now_add=True,)
    start = models.DateTimeField(blank=True, null=True,)
    end_time = models.TimeField(blank=True, null=True,)
    competitive = models.BooleanField(default=False,)

Filtering

filtered_sessions = Session.objects.filter(
    start__week_day=2,
).exclude(start__isnull=True)

I currently have an entry in the sessions table (MySQL backend) which contains the datetime 2018-04-30 23:51:42.000000, so I would expect this QuerySet to contain that 'Session' as it occurs on a Monday.

Referring back to the documentation, The week goes from Sunday(1) to Saturday(7).
I have USE_TZ in my settings, TIME_ZONE='UTC'.
Irrespective of these settings, I have also tried replacing the start__week_day=2 with values from 0-8 (inclusive, just in case)

My question is this: Why is what I am trying is not returning any results?

Please let me know if I've left out something that would help answer my query.
Thanks!

EDIT: I have since attempted to run a direct query in the database (SELECT * FROM mysite_session WHERE DAYOFWEEK('start') IN (0-8);)
No result in the database.

Upvotes: 0

Views: 900

Answers (1)

James M.
James M.

Reputation: 11

After a few hours more of research and testing, it turns out that my issue was indeed due to USE_TZ, but not directly.

The problem was that I didn't import my timezones correctly into my MySQL database.
Firstly, I didn't have the required tables (which I found here on lines 60-72)
Secondly, I didn't correctly set up my timezones.
I ran mysql_tz_info_to_sql /usr/share/zoneinfo | mysql -u root
where I should've ran
mysql_tz_info_to_sql /usr/share/zoneinfo/ | mysql -u root mysql

After correctly running that command and ensuring that I did indeed have the tables in my database, I was able to execute the Django Filter successfully.

Thank you to everyone who helped, as I wouldn't have discovered the issue without your input!

Upvotes: 1

Related Questions