pynamodb / PynamoDB

A pythonic interface to Amazon's DynamoDB
http://pynamodb.readthedocs.io
MIT License
2.44k stars 427 forks source link

deserialize is not called for null values #1255

Open Ted-Barrett opened 3 weeks ago

Ted-Barrett commented 3 weeks ago

I would like to handle null values when deserializing. I have the following custom attribute:

class TestAttribute(Attribute):
    attr_type = BINARY

    def serialize(self, value: Any) -> Any:
        return json.dumps(value)
    def deserialize(self, value: Any) -> Any:
        raise RuntimeError("STOP!!")

being used in a model:

class MyModel(Model):
    test_field = TestAttribute(null=True)

If the field has data in it, I get the runtime error STOP!! as expected.

If the field is empty, there is no such error, and e.test_field is None.

How can I handle the behaviour when a value is null?

ikonst commented 2 weeks ago

Unfortunately this check simply won't let you have that: https://github.com/pynamodb/PynamoDB/blob/4b8630409b46cd57ccbb08658c71bda339c9df7e/pynamodb/attributes.py#L431-L432

(Curiously, the NULL DynamoDB attribute value would also have the same effect, making it indistinguishable from absence of value. A shame.)

Typically I'd override a model's deserialize if I want the opportunity to work with the raw data before field-by-field deserialization.