代码应该从CSV中获取由另一种方法生成的字典 - 并生成所有必需的客户和订单实体。
def loadOrderData(fileName,session):
print("Orders loading")
liDict = Loader.csv2liDict(fileName, {1: "date", 16: "customerName", 22: "customerPostcode", 23: "salesOrderNo",
25: "worksOrderNo", 35: "productCode", 38: "width", 39: "length",
53: "quantity"})
for i in liDict:
customerId = -1
for j in session.query(Customer.id). \
filter(Customer.name == i["customerName"]). \
filter(Customer.postcodeDistrict == i["customerPostcode"].split(" ")[0]):
customerId = j
if customerId == -1:
newCustomer = Customer(name=i["customerName"], postcodeDistrict=i["customerPostcode"].split(" ")[0])
session.add(newCustomer)
session.commit()
customerId = newCustomer.id
print("CUSTOMER ID : ",customerId)
newOrder = Order(date=str2date(i["date"]), customerId=customerId, salesOrderNo=i["salesOrderNo"],
worksOrderNo=i["worksOrderNo"], productCode=i["productCode"], width=int(i["width"]),
length=int(i["length"]), quantity=int(i["quantity"]))
session.add(newOrder)
session.commit()
我一直收到以下错误:
sqlalchemy.exc.InterfaceError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (sqlite3.InterfaceError) Error binding parameter 1 - probably unsupported type. [SQL: 'INSERT INTO "order" (date, "customerId", "worksOrderNo", "salesOrderNo", "productCode", width, length, quantity, assigned) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'] [parameters: ('2016-10-26 00:00:00.000000', (1,), '', 'S/O269155', 'BKT1', 724, 1769, 0, None)]
基本上,我推断它是由于customerId等于(1,)而不是int。但是,我不明白为什么会发生这种情况以及如何解决这个问题。建议,请。
答案 0 :(得分:2)
可以看到here,通过用逗号分隔项来创建元组(1,)
。可以使用尾随逗号创建一个项目元组,这通常会引起混淆。
customerId = 1,
尝试调试这些情况时,最好将注意力集中在项目的创建位置。在你的例子的情况下,我建议从csv解析开始,但由于我无法运行此代码,我不能再给出具体的建议。
更新
根据roganjosh的评论,该项目由查询返回。它设置的查询接口使得可以返回多个结果,因此可能返回元组。您应该调查Query.one()或Query.one_or_none。
答案 1 :(得分:0)
我自己找到了答案:我复制了循环查询并将其放在if customerId == -1语句的末尾,如下所示:
for j in session.query(Customer.id). \
filter(Customer.name == i["customerName"]). \
filter(Customer.postcodeDistrict == i["customerPostcode"].split(" ")[0]):
customerId = j[0]
if customerId == -1:
newCustomer = Customer(name=i["customerName"], postcodeDistrict=i["customerPostcode"].split(" ")[0])
session.add(newCustomer)
session.commit()
for j in session.query(Customer.id). \
filter(Customer.name == i["customerName"]). \
filter(Customer.postcodeDistrict == i["customerPostcode"].split(" ")[0]):
customerId = j[0]