Skip to main content
 首页 » 编程设计

Python:循环 NDB 实体模型

2025年05月04日12zhujiabin

我有一个定义如下的类/NDB 实体模型:

class CashModel(ndb.Model): 
    "Models a Cash record" 
    # Name, Balance, Interest Rate 
    accountName = ndb.StringProperty() 
    interestRate = ndb.FloatProperty() 
    balance = ndb.FloatProperty() 
    accountType = ndb.StringProperty() 
    futureView = ndb.JsonProperty() 
    time_stored = ndb.DateTimeProperty(auto_now_add=True) 

将值添加到 class 后,它的打印结果如下所示:

CashModel(accountName=u'Bank', accountType=u'cash', balance=1000.0, futureView=None, interestRate=5.0, time_stored=datetime.datetime(2015, 7, 7, 18, 33, 3, 925601)) 

我如何遍历此类的键/值对,以便输出类似于:

accountName, Bank 
accountType, cash 
balance, 1000.0 
futureView, None 
interestRate, 5.0 
time_stored, datetime.datetime(2015, 7, 7, 18, 33, 3, 925601) 

查看了 S.O. 上的其他答案,但似乎没有一个合适。使用内置方法的简单解决方案将是最好的。时间差

请您参考如下方法:

您可以使用 to_dict(include=None, exclude=None) 实例方法将模型对象转换为字典,然后使用 iteritems() 迭代键/值对

to_dict(include=None, exclude=None) 

返回包含模型属性值的字典。

Check this link