Opened 14 years ago

Closed 14 years ago

Last modified 12 years ago

#12546 closed (fixed)

Definining __len__ on a model object breaks it's serialization

Reported by: casbon Owned by: Natalia Bidart
Component: Core (Other) Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In line 37 of django.core.serializers.python you have:

    def handle_field(self, obj, field):
        value = field._get_val_from_obj(obj)

This calls django.db.models.fields.init line 274:

    def _get_val_from_obj(self, obj):
        if obj:
            return getattr(obj, self.attname)
        else:
            return self.get_default()

Now suppose obj has a len which is returning zero. This means 'if obj' is False, then this method returns the default value rather than the object's value.

Suugested fix is to change 'if obj' to 'if obj is not None'.

Attachments (1)

django-len-serialization.diff (2.1 KB ) - added by Alex Gaynor 14 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 by Claude Paroz, 14 years ago

Been confronted to the same issue today. On one side, the object can workaround this by defining the __nonzero__ method (see http://docs.python.org/reference/datamodel.html#object.__len__). On the other side, the test here is not to know if the object evaluates to True or False, but if it can be queried for the attribute.

What about:

def _get_val_from_obj(self, obj):
    return getattr(obj, self.get_attname(), self.get_default())

comment:2 by Russell Keith-Magee, 14 years ago

milestone: 1.2
Triage Stage: UnreviewedAccepted

by Alex Gaynor, 14 years ago

comment:3 by Natalia Bidart, 14 years ago

Owner: changed from nobody to Natalia Bidart
Status: newassigned

comment:4 by jkocherhans, 14 years ago

Resolution: fixed
Status: assignedclosed

(In [12576]) Fixed #12546. Objects with a len that returns 0 can now be serialized. Thanks, casobn for the report and Alex Gaynor for the patch and tests.

comment:5 by jkocherhans, 14 years ago

(In [12577]) [1.1.X] Fixed #12546. Objects with a len that returns 0 can now be serialized. Thanks, casobn for the report and Alex Gaynor for the patch and tests. Backport of r12576 from trunk.

comment:6 by Jacob, 12 years ago

milestone: 1.2

Milestone 1.2 deleted

Note: See TracTickets for help on using tickets.
Back to Top