#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 by , 16 years ago
comment:2 by , 16 years ago
| milestone: | → 1.2 |
|---|---|
| Triage Stage: | Unreviewed → Accepted |
by , 16 years ago
| Attachment: | django-len-serialization.diff added |
|---|
comment:3 by , 16 years ago
| Owner: | changed from to |
|---|---|
| Status: | new → assigned |
comment:4 by , 16 years ago
| Resolution: | → fixed |
|---|---|
| Status: | assigned → closed |
comment:5 by , 16 years ago
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:
def _get_val_from_obj(self, obj): return getattr(obj, self.get_attname(), self.get_default())