Hey everyone (Russ in particular), it's me again.

While working on DurationField recently, I noticed what I thought to
be strange behavior during serialization. The XML serializer worked as
I expected, using the number of seconds as a decimal, while the JSON
serializer used the output of str(), which is a human-readable string.
This meant that XML-serialized data could be deserialized correctly,
while the JSON data threw an error, since DurationField's to_python
didn't know how to handle that format.

Looking at the guts of serialization today, I see that the difference
is in handle_field(). The XML serializer calls get_string_value(),
which is implemented in the base class, and that method uses the
field's flatten_data() method to get the string representation. Since
DurationField is written to work with oldforms (namely the admin),
flatten_data() returns the decimal form and all works well.

The JSON serializer, however, extends the Python serializer, whose
handle_field() blindly calls smart_unicode() on the value, without
regard for the field's flatten_data() method. And since
force_unicode() doesn't make an exception for timedelta objects, it
just uses the str() output.

In the wake of Malcolm's recent work on Field subclassing, it seems
like this discrepancy could cause more problems in the long run. From
what I can see, the only solution without patching core is to modify
DurationField's to_python() to also accommodate timedelta's str()
format, which isn't something I'm looking forward to. I'll do it if I
need to, though.

On a more general scale though, the new documentation states that
flatten_data() "is used by the serializers to convert the field into a
string for output," but clearly only the XML serializer does so. In
order to properly work with the others, to_python() must also support
whatever format the object's str() output looks like. In the case of
the provided example, this would be simple, since Hand could implement
__str__ to match the get_db_prep_save() output, but in cases like
DurationField, I'm not in control of the str() output.

Can anybody with more experience with serializers help explain why
this discrepancy exists, and what's the best way to go about handling
it? I'll gladly submit a ticket if it's necessary, but I have a
sneaking suspicion that I'm missing something subtle here. And, while
I hope the answer isn't, "yes, to_python() should always support the
object's str() format," I'll accept that if it is indeed the case.
I'll just file a documentation ticket instead.

-Gul

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to