PynamoDB icon indicating copy to clipboard operation
PynamoDB copied to clipboard

UpdateItem operation based on a dict

Open isdaves opened this issue 3 years ago • 3 comments

Hi,

The quickstart in the docs warns against using save() to perform updates on sets of attributes of an item lest you overwrite to None all the missing attributes in your object.

When writing an API, I typically get a dict type structure of key:value pairs to be updated, but I want only those to be done. In this scenario, save() is really useful since I can create a Model object with the dict directly, and then save it.

Note that the hash/range keys are always included, in my case.

my_input_dict = {'hash_key': 'foo', 'range_key': 'bar', 'new_attr': 'hoge'}
MyModel(**my_input_dict).save()

Is there any way to do the same for update() ?

As far as I can see, it expects you to add Actions, but will not accept just a dict with the updates. Needless to say, I want to avoid having to use low level calls.

Thanks!

isdaves avatar Apr 16 '21 05:04 isdaves

Forgot to say, the main reason for this approach is to save one full read from the DB, and allow updating directly only the attributes that you want.

isdaves avatar Apr 19 '21 09:04 isdaves

+1 to this use case. With previous versions the Model class implemented as_dict() method that allowed us to update fields based on a dict. Since that was removed this is not the case anymore.

abend-arg avatar Jun 06 '23 12:06 abend-arg

Doesn't seem too hard to do:

m = MyModel(hk, rk)
m.update(
  actions=[
    getattr(MyModel, k).set(v)
    for k, v in d.items()
  ],
)

ikonst avatar Jun 06 '23 17:06 ikonst