Code

Opened 4 years ago

Closed 4 years ago

Last modified 3 years ago

#12546 closed (fixed)

Definining __len__ on a model object breaks it's serialization

Reported by: casbon Owned by: nessita
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: UI/UX:

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 4 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 Changed 4 years ago by claudep

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

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 Changed 4 years ago by russellm

  • milestone set to 1.2
  • Triage Stage changed from Unreviewed to Accepted

Changed 4 years ago by Alex

comment:3 Changed 4 years ago by nessita

  • Owner changed from nobody to nessita
  • Status changed from new to assigned

comment:4 Changed 4 years ago by jkocherhans

  • Resolution set to fixed
  • Status changed from assigned to closed

(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 Changed 4 years ago by jkocherhans

(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 Changed 3 years ago by jacob

  • milestone 1.2 deleted

Milestone 1.2 deleted

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.