Created
July 12, 2016 13:50
-
-
Save mjrulesamrat/8afeb693bb1dcb1cf4c64b6825cd2748 to your computer and use it in GitHub Desktop.
Custom transform for django date filter. It works like charm. :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models import Transform | |
# Custom Date filter transform class | |
# Added by : Jay Modi | |
class MySQLDatetimeDate(Transform): | |
""" | |
This implements a custom SQL lookup when using `__date` with datetimes. | |
To enable filtering on datetimes that fall on a given date, import | |
this transform and register it with the DateTimeField. | |
http://blog.zdsmith.com/comparing-dates-and-datetimes-in-the-django-orm.html | |
""" | |
lookup_name = 'customdate' | |
def as_sql(self, compiler, connection): | |
lhs, params = compiler.compile(self.lhs) | |
return 'DATE({})'.format(lhs), params | |
@property | |
def output_field(self): | |
return models.DateField() | |
# https://docs.djangoproject.com/en/1.8/howto/custom-lookups/#a-simple-transformer-example | |
# Added by : Jay Modi | |
from django.db.models import DateField | |
DateField.register_lookup(MySQLDatetimeDate) | |
dt = datetime.strptime(year+"/"+month+"/"+day, "%Y/%m/%d").date() | |
modelobj.objects.filter(date__customdate = dt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment