Django queryset filtering by ISO week number

与世无争的帅哥 提交于 2019-12-03 11:59:33

You're not going to be able to do this. Remember it's not just an issue of what Python supports, Django has to communicate the filter to the database, and the database doesn't support such complex date calculations. You can use __range, though, with a start date and end date.

(This answer should only work for postgres, but might work for other databases.)

A quick and elegant solution for this problem would be to define these two custom transformers:

from django.db import models
from django.db.models.lookups import DateTransform

@models.DateTimeField.register_lookup
class WeekTransform(DateTransform):
    lookup_name = 'week'


@models.DateTimeField.register_lookup
class ISOYearTransform(DateTransform):
    lookup_name = 'isoyear'

Now you can query by week like this:

from django.utils.timezone import now
year, week, _ = now().isocalendar()

MyModel.objects.filter(created__isoyear=year, created__week=week)

Behinds the scenes, the Django DateTransform object uses the postgres EXTRACT function, which supports week and isoyear.

ExtractWeek has been introduced in Django 1.11 for filtering based on isoweek number.

For Django 1.10 and lower versions, following solution works for filtering by iso number week on postgres database:

from django.db.models.functions import Extract
from django.db import models
@models.DateTimeField.register_lookup
class ExtractWeek(Extract):
    lookup_name = 'week'

Now do query as follows

queryset.annotate(week=ExtractWeek('date'))\
            .filter(week=week_number)

Even simpler than using Extract function that Amit mentioned in his answer is using __week field lookup added in Django 1.11, so you can simply do:

.filter(model__date__week=datetime.date.today().isocalendar()[1])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!