From 7f71ae1b8dcbd2c74f53e479577f165e178df93c Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 2 Nov 2006 14:24:31 +0000 Subject: [PATCH] Fixes #2918 -- Clarified the db_prep_save logic for DateField and DateTimeField to prevent accidental conversion of non-datetime objects into strings, because SQLite doesn't appear to check for valid date format in a string used on an UPDATE of a datetime column. git-svn-id: http://code.djangoproject.com/svn/django/trunk@3960 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/__init__.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index d82f38527d..2ec5e8c7c7 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -457,7 +457,9 @@ class DateField(Field): def get_db_prep_save(self, value): # Casts dates into string format for entry into database. - if value is not None: + if isinstance(value, datetime.datetime): + value = value.date().strftime('%Y-%m-%d') + elif isinstance(value, datetime.date): value = value.strftime('%Y-%m-%d') return Field.get_db_prep_save(self, value) @@ -487,12 +489,19 @@ class DateTimeField(DateField): def get_db_prep_save(self, value): # Casts dates into string format for entry into database. - if value is not None: + if isinstance(value, datetime.datetime): # MySQL will throw a warning if microseconds are given, because it # doesn't support microseconds. if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): value = value.replace(microsecond=0) value = str(value) + elif isinstance(value, datetime.date): + # MySQL will throw a warning if microseconds are given, because it + # doesn't support microseconds. + if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): + value = datetime.datetime(value.year, value.month, value.day, microsecond=0) + value = str(value) + return Field.get_db_prep_save(self, value) def get_db_prep_lookup(self, lookup_type, value):