Skip to content

Instantly share code, notes, and snippets.

@mjrulesamrat
Created July 12, 2016 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjrulesamrat/8afeb693bb1dcb1cf4c64b6825cd2748 to your computer and use it in GitHub Desktop.
Save mjrulesamrat/8afeb693bb1dcb1cf4c64b6825cd2748 to your computer and use it in GitHub Desktop.
Custom transform for django date filter. It works like charm. :)
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