1

我无法从 PynamoDB 实例获取 JSON 表示。这是模型。

class MyTest(Model):
    """
    Model class representing the Golden table attributes.
    """

    class Meta:
        table_name = "my-test"

    # Query Fields
    Id = UnicodeAttribute(hash_key=True)
    SomeInfo = MapAttribute(default={})
    SomeInfo1 = UnicodeAttribute(null=True)
my_test = MyTest(Id='123', SomeInfo={}, SomeInfo1='testing')

我需要的是 my_test 的 JSON 表示。

我尝试过的事情是。

  1. my_test.to_dict() - 这给出了一个非属性错误

  2. json.dumps(my_test.to_dict(), 缩进=2)

任何帮助,将不胜感激。

4

3 回答 3

3

如果您希望dict摆脱 pynamoDB 模型,可以尝试使用该attribute_values属性:

# Define the model
class Car(Model):
    class Meta:
        table_name = "cars"

    # Query Fields
    vin = UnicodeAttribute(hash_key=True)
    make = UnicodeAttribute(null=True)
    model = UnicodeAttribute(null=True)

# Create instance
new_car = Car("123F345", "Honda", "Civic")

# Read back the attributes
attrs = new_car.attribute_values // {"vin": "123F345", "make": "Honda", "model": "Civic"} 

结果attrs将是简单的dict( <class 'dict'>)

示例用例(仅用于说明):

// List of dict with the results of a scan of the whole Cars table
results = [car.attribute_values for Cars.scan()]   ​
于 2021-03-25T02:08:03.760 回答
0

PynamoDB最近添加 to_json了对象和from_json函数Model

然而,截至目前,它在多态模型/属性方面存在一些错误,阻碍了正确的反序列化。

我确实有一个支持多态模型/属性的不同实现。这个更灵活一点,恕我直言。

于 2021-12-13T18:39:40.520 回答
0

所以,我遇到了同样的问题,唯一对我有用的是将每个属性映射到其特定类型并相应地处理它,如下所示:

def __iter__(self):
        for name, attr in self.get_attributes().items():
            if isinstance(attr, MapAttribute):
                if getattr(self, name):
                    yield name, getattr(self, name).as_dict()
            elif isinstance(attr, UTCDateTimeAttribute):
                if getattr(self, name):
                    yield name, attr.serialize(getattr(self, name))
            elif isinstance(attr, NumberAttribute):
                yield name, getattr(self, name)
            else:
                yield name, attr.serialize(getattr(self, name))
于 2020-10-08T01:32:06.710 回答