gpt4 book ai didi

python - 创建 sqlalchemy 对象时循环字段

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:10 25 4
gpt4 key购买 nike

我正在尝试循环通过 json 收到的字典,并通过 sqlalchemy 将结果保存到数据库。我将字段名称与字典中的键名称保持相同。一遍又一遍地列出每个字段和字典似乎是重复的。但是当我尝试使用 c.keys() 之类的东西时,它不起作用。如果是这样的话我可以这样做: 对于 c.keys() 中的键: 客户.key = c[key]

但这不起作用。我当前的代码是:

for c in response['Customers']:
customer = Customer()
customer.ID = c['ID']
customer.Name = c['Name']
customer.Currency = c['Currency']
customer.PaymentTerm = c['PaymentTerm']
customer.Discount = c['Discount']
customer.TaxRule = c['TaxRule']
customer.Carrier = c['Carrier']
session.add(customer)
session.commit()

最佳答案

您可以使用Python的setattr函数,根据 document :

setattr(object, name, value)

The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.

For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

因此您可以将代码编写为:

for c in response['Customers']:
customer = Customer()
for key, value in c.items():
setattr(customer, key, value)
# ^ usage of `setattr(...)` here
session.add(customer)

session.commit()

我假设您的类中定义了与 dict 对象 c 中存在的键相对应的所有属性。

关于python - 创建 sqlalchemy 对象时循环字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44894365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com