我在从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表示。
我尝试过的事情是。
任何帮助都将不胜感激。
发布于 2021-03-25 02:08:03
如果您希望从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-12-13 18:39:40
发布于 2020-10-08 01:32:06
因此,我遇到了同样的问题,唯一有效的方法就是将每个属性映射到它的特定类型,并相应地处理它:
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))https://stackoverflow.com/questions/61821580
复制相似问题