Skip to content

Commit

Permalink
explicitly set current Django timezone for Date & DateTime fields
Browse files Browse the repository at this point in the history
  • Loading branch information
stebunovd committed Aug 4, 2017
1 parent 8e7bce7 commit 87958ad
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
19 changes: 15 additions & 4 deletions djangoql/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.contrib.contenttypes.fields import GenericRel
from django.db import models
from django.db.models import FieldDoesNotExist, ManyToManyRel, ManyToOneRel
from django.utils.timezone import get_current_timezone

from .ast import Comparison, Const, List, Logical, Name, Node
from .compat import text_type
Expand Down Expand Up @@ -179,10 +180,15 @@ class DateField(DjangoQLField):
value_types = [text_type]
value_types_description = 'dates in "YYYY-MM-DD" format'

def get_lookup_value(self, value):
return datetime.strptime(value, '%Y-%m-%d').replace(
tzinfo=get_current_timezone(),
)

def validate(self, value):
super(DateField, self).validate(value)
try:
datetime.strptime(value, '%Y-%m-%d')
self.get_lookup_value(value)
except ValueError:
raise DjangoQLSchemaError(
'Field "%s" can be compared to dates in '
Expand All @@ -198,15 +204,20 @@ class DateTimeField(DjangoQLField):
value_types = [text_type]
value_types_description = 'timestamps in "YYYY-MM-DD HH:MM" format'

def validate(self, value):
super(DateTimeField, self).validate(value)
def get_lookup_value(self, value):
mask = '%Y-%m-%d'
if len(value) > 10:
mask += ' %H:%M'
if len(value) > 16:
mask += ':%S'
return datetime.strptime(value, mask).replace(
tzinfo=get_current_timezone(),
)

def validate(self, value):
super(DateTimeField, self).validate(value)
try:
datetime.strptime(value, mask)
self.get_lookup_value(value)
except ValueError:
raise DjangoQLSchemaError(
'Field "%s" can be compared to timestamps in '
Expand Down
7 changes: 5 additions & 2 deletions test_project/core/tests/test_queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,13 @@ def get_fields(self, model):

class DjangoQLQuerySetTest(TestCase):
def test_simple_query(self):
qs = Book.objects.djangoql('name = "foo" and author.email = "bar@baz"')
qs = Book.objects.djangoql(
'name = "foo" and author.email = "em@il" and written > "2017-01-30"'
)
where_clause = str(qs.query).split('WHERE')[1].strip()
self.assertEqual(
'("core_book"."name" = foo AND "auth_user"."email" = bar@baz)',
'("core_book"."name" = foo AND "auth_user"."email" = em@il '
'AND "core_book"."written" > 2017-01-30 00:00:00)',
where_clause,
)

Expand Down

0 comments on commit 87958ad

Please sign in to comment.