创建sqlalchemy obj时遍历字段

2024-10-01 04:58:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但这行不通。我目前的代码是:

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()

Tags: nameid数据库jsonsqlalchemysessiondiscountcustomer
2条回答

您可以只使用unpack your dictionaries as arguments到{},前提是您没有重写与另一个答案完全相同的default constructor provided by Declarative;它从关键字参数设置属性:

for c in response['Customers']:
    session.add(Customer(**c))

session.commit()

您可以使用Python的^{}函数,根据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中的键相对应的所有属性。在

相关问题 更多 >