Opened 8 years ago

Closed 8 years ago

#14037 closed (duplicate)

models.DateField don't serialize JSON

Reported by: Carlo Pires Owned by: nobody
Component: Database layer (models, ORM) Version: 1.2
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


When serializing records with DateField(auto_now=True), the serialized
string is incorrect because created record is initialized with date.datetime
and django.core.serializers.Serializer.handle_field don't call
DateField.value_to_string() as date.datetime is listed in

Start an app called bugmodel and create:

from django.db import models

class BugSerial(models.Model):
        date = models.DateField(auto_now=True)

Now, after syncdb, the bug:

./ shell
In [1]: from bugmodel.models import BugSerial

In [2]: r = BugSerial()

In [3]:

In [4]: from django.core.serializers import serialize

In [5]: serialized = serialize('json', [r])

In [6]: serialized
Out[6]: '[{"pk": 1, "model": "bugmodel.bugserial", "fields": {"date": "2010-07-30 14:24:09"}}]'

In [7]: from django.core.serializers import deserialize

In [8]: unserialized = deserialize('json', serialized)

In [9]: unserialized
Out[9]: <generator object Deserializer at 0x187d0f0>

In [10]: list(unserialized)
ValidationError                           Traceback (most recent call last)

/home/carlo/bug/bug/<ipython console> in <module>()

/usr/lib/python2.6/dist-packages/django/core/serializers/ in Deserializer(stream_or_string, **options)
     36     else:
     37         stream = stream_or_string
---> 38     for obj in PythonDeserializer(simplejson.load(stream), **options):
     39         yield obj

/usr/lib/python2.6/dist-packages/django/core/serializers/ in Deserializer(object_list, **options)
    126             # Handle all other fields

    127             else:
--> 128                 data[] = field.to_python(field_value)
    130         yield base.DeserializedObject(Model(**data), m2m_data)

/usr/lib/python2.6/dist-packages/django/db/models/fields/ in to_python(self, value)
    607         if not
--> 608             raise exceptions.ValidationError(self.error_messages['invalid'])
    609         # Now that we have the date string in YYYY-MM-DD format, check to make

    610         # sure it's a valid date.

ValidationError: [u'Enter a valid date in YYYY-MM-DD format.']

Change History (3)

comment:1 Changed 8 years ago by Ramiro Morales

Component: UncategorizedDatabase layer (models, ORM)

I think this is a duplicate of #10970 (and #10602 that IMHO was incorrectly closed as invalid.)

comment:2 Changed 8 years ago by Carlo Pires

I think this is a bug. models.DateField with auto_now should use as init value.

comment:3 Changed 8 years ago by Ramiro Morales

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top