Skip to content

Instantly share code, notes, and snippets.

Created July 12, 2016 13:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
lookup_name = 'customdate'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'DATE({})'.format(lhs), params
def output_field(self):
return models.DateField()
# Added by : Jay Modi
from django.db.models import DateField
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