Emitters don't allow non-field attributes that evaluate to False

Issue #108 duplicate
Khalid Goudeaux
created an issue

The below section of the model handler code is for non Django-field attributes on a model. If you have an attribute on your model that is not a function and evaluates to False, it may be excluded from the emitter output.

i.e. bool(0), bool(False), bool(None), bool(''), bool([]), bool({}) - attributes with these values will disappear from the result (if they also don't have corresponding methods on the handler)

It would be better to check if the object has the attribute and if so, check if it's callable or return _any(maybe)

{{{ maybe = getattr(data, maybe_field, None) if maybe: if callable(maybe): if len(inspect.getargspec(maybe)[0]) == 1: ret[maybe_field] = _any(maybe()) else: ret[maybe_field] = _any(maybe) else: handler_f = getattr(handler or self.handler, maybe_field, None)

if handler_f:
    ret[maybe_field] = _any(handler_f(data))


Perhaps something like: {{{ if hasattr(data, maybe_field): maybe = getattr(data, maybe_field) if callable(maybe): pass else: _any else: check_handler }}}

Comments (4)

  1. Benoit Clennett-Sirois

    My 2 cents: I noticed this happens when you turn a model's method to a "property" using the @property decorator. If the bool(result of function) evaluates to False, django-piston will search for a function with the same field name in your handler, so you can define one of you want. Else it will not include the field and result.


    class Authorization(models.Model):
        amount = models.DecimalField(
            _('Amount'), decimal_places=2, max_digits=8)
        #....more code....
        def completed(self):
            return False

    Sample result: One includes "completed" because it evaluates to True, the other one doesn't.

        "authorizations": [
                "first_name": "", 
                "last_name": "", 
                "order_id": "abc123", 
                "completed_amount": "0", 
                "completed_date": null, 
                "amount": "2", 
                "time_stamp": "2011-07-21 12:54:32", 
                "email": "", 
                "transaction_id": "derp1"
                "first_name": "", 
                "last_name": "", 
                "order_id": "asdads", 
                "completed_date": "2011-07-21 13:36:47", 
                "completed_amount": "2", 
                "completed": true, 
                "amount": "7", 
                "time_stamp": "2011-07-21 13:36:26", 
                "email": "", 
                "transaction_id": "asdasdsa"

    I just decided not to use @property as a workaround.

  2. Log in to comment