#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)
Change History (7)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
milestone: | → 1.2 |
---|---|
Triage Stage: | Unreviewed → Accepted |
Changed 9 years ago by
Attachment: | django-len-serialization.diff added |
---|
comment:3 Changed 9 years ago by
Owner: | changed from nobody to Natalia Bidart |
---|---|
Status: | new → assigned |
comment:4 Changed 9 years ago by
Resolution: | → fixed |
---|---|
Status: | assigned → closed |
comment:5 Changed 9 years ago by
Note: See
TracTickets for help on using
tickets.
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: