PynamoDB icon indicating copy to clipboard operation
PynamoDB copied to clipboard

Pynamodb Update Operation append() doesn't work with List of Unicode or Number

Open MacHu-GWU opened this issue 3 years ago • 7 comments

There's no example available in document to show how to append an element to a list in dynamodb. This is the code to reproduce this error:


class DataModel(Model):
    class Meta:
        table_name = "test"
        region = "us-east-1"
        billing_mode = pynamodb.models.PAY_PER_REQUEST_BILLING_MODE

    id = UnicodeAttribute(hash_key=True)
    list = ListAttribute(of=NumberAttribute, default=list)
    
DataModel(id="i-1").save()

DataModel(id="i-1").update(
    actions=DataModel.list.append(1),
    condition=DataModel.id.exists()
)    # ValueError: The data type of '{'N': '1'}' must be one of ['L']

MacHu-GWU avatar Jun 22 '21 00:06 MacHu-GWU

I think I figured it out in like 10 minutes. In the test case, I find a test case for append here https://github.com/pynamodb/PynamoDB/blob/master/tests/test_expressions.py#L500. I think you need to add this example to the docs:

The correct way to do it is:

DataModel(id="i-1:").update(
    actions=DataModel.list.set(
        DataModel.list.append([1,])
    ),
    ...
)

MacHu-GWU avatar Jun 22 '21 00:06 MacHu-GWU

Previously: https://github.com/pynamodb/PynamoDB/issues/434

Yep, we need to document this!

ikonst avatar Jun 22 '21 01:06 ikonst

https://github.com/pynamodb/PynamoDB/pull/951

btw, it is documented here, but I admit it took me a while to find: https://pynamodb.readthedocs.io/en/latest/updates.html#update-expressions

ikonst avatar Jun 22 '21 01:06 ikonst

@ikonst document at https://pynamodb.readthedocs.io/en/latest/updates.html#update-expressions is WRONG

it says: Thread.notes.append([‘my last note’]), but it should be Thread.notes.set(Thread.notes.append([‘my last note’]))

MacHu-GWU avatar Jun 22 '21 03:06 MacHu-GWU

The documentation shows how DynamoDB actions map to PynamoDB syntax, not how to use DynamoDB actions to do practical things :)

That's how DynamoDB structures it: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html#DDB-UpdateItem-request-UpdateExpression

What you'd want is a code sample.

ikonst avatar Jun 22 '21 03:06 ikonst

@ikonst this makes perfect sense. Hope this thread can help other people having similar questions. Thank you for your great answer !

MacHu-GWU avatar Jun 22 '21 06:06 MacHu-GWU

It looks like there is place where a list update code sample can fit in. https://pynamodb.readthedocs.io/en/latest/attributes.html#list-attributes

aczire avatar Apr 12 '22 20:04 aczire