{{{
# models.py
from django.db import models
class SomeModel(models.Model):
some_datetime = models.DateTimeField()
}}}
{{{
# Script which you want to serialize model
from django.core import serializers
from MyAPP.models import SomeModel
some_model = SomeModel(some_datetime="2017-02-02T00:00:00")
# We didn't have problem if you save it
some_model.save()
# But if you tried to serialize it, you got an error, because inside
method
# it expected `datetime` object and it will raise an exception
# `AttributeError: 'str' object has no attribute 'isoformat'`
serialized_object = serializers.serialize('json', [some_model])
}}}
To fix it, we need to check if value is a string, and if have a valid
format (using `parse_datetime` function), if is `None` we raise an
exception (`ValidationError`).
--
Ticket URL: <https://code.djangoproject.com/ticket/28356>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* owner: nobody => Hermogenes Batista da Silva Filho
* status: new => assigned
--
Ticket URL: <https://code.djangoproject.com/ticket/28356#comment:1>
* component: Uncategorized => Database layer (models, ORM)
Comment:
This doesn't strike me as a bug. I think your script should take care of
parsing the string so a date or datetime is assigned. Is there a problem
with that approach?
--
Ticket URL: <https://code.djangoproject.com/ticket/28356#comment:2>
Comment (by Hermogenes Batista da Silva Filho):
I thinking it like a bug, because when I was saving, this format (string
instead date/datetime) is accepted and it will saved without problem, so
this behavior must be equals on serializer too.
--
Ticket URL: <https://code.djangoproject.com/ticket/28356#comment:3>
Comment (by Hermogenes Batista da Silva Filho):
Also, when you save your instance with this value, and have implemented
one `post_save` to serialize it and send to Kafka (for example), the
instance received on signal, will have that field with string yet, so we
got this problem (this is my scenario).
--
Ticket URL: <https://code.djangoproject.com/ticket/28356#comment:4>
* status: assigned => closed
* resolution: => wontfix
Comment:
I'm still not convinced that Django should head down the path of trying to
handle field types that are different from the type that's retrieved from
the database (see #27825 for another case). Just because strings happen to
work to saving a model instance doesn't mean that the Django ecosystem
should be prepared to handle a string for these fields -- that'll add a
lot of complexity. Also, the usual case for serializers is to handle
objects from the database, not unsaved model instances, so my opinion is
that fixing this in your code is more appropriate than adding more
complexity to Django. If you still disagree, feel free to write to the
DevelopersMailingList to get other opinions.
--
Ticket URL: <https://code.djangoproject.com/ticket/28356#comment:5>