0

我需要用 PynamoDB 库实例化一个使用本地二级索引的类模型,但我遇到了错误。我的代码:

class MyIndex(LocalSecondaryIndex):
    
    class Meta:
        projection = AllProjection()
    
    org_id = UnicodeAttribute(hash_key=True)
    user_id = UnicodeAttribute(range_key=True)


class MyModel(Model):
    
    class Meta:
        table_name = 'my-table'
        region = 'eu-west-1'
        aws_access_key_id = '...'
        aws_secret_access_key = '...'
    
    org_id = UnicodeAttribute(hash_key=True)
    doc_id = UnicodeAttribute(range_key=True)
    user_index = MyIndex()

    attr_one = NumberAttribute()
    attr_two = UnicodeAttribute()
    attr_three = NumberAttribute()

这是我第一次在 PynamoDB 中使用索引(本地或全局)。文档实际上并没有给出使用索引实例化模型类的示例(我已经看到),只是模型/索引定义以及查询示例(我指的是readthedocs heregithub examples here) .

我第一次尝试测试这个看起来像这样:

MyModel(
    org_id = my_org_id,
    doc_id = my_doc_id,
    user_index = MyIndex(my_org_id, 'abc123'),
    attr_one = 1,
    attr_two = 'foo',
    attr_three = 3,
)

...但我在MyIndex构造函数中收到以下错误:

TypeError: __init__() takes 1 positional argument but 3 were given

删除第一个参数my_org_id给了我上面的错误...but 2 were given。我也尝试过user_index = 'abc123'user_id = 'abc123'但在这两种情况下我都得到了ValueError: Attribute user_* specified does not exist.

有人可以告诉我这应该如何工作或向我指出一个工作示例的方向吗?

4

1 回答 1

0

我只是从示例中意识到,在 LSI 中使用的排序键还必须使用 LSI 指定为表上的属性,以便使其正常工作,例如

class MyModel(Model):

    class Meta:
        table_name = 'my-table'
        region = 'eu-west-1'
        aws_access_key_id = '...'
        aws_secret_access_key = '...'

    org_id = UnicodeAttribute(hash_key=True)
    doc_id = UnicodeAttribute(range_key=True)
    user_index = MyIndex()
    user_id = UnicodeAttribute() ### this was missing
于 2021-05-05T08:47:30.363 回答