我需要将数据从csv文件保存到django模型。数据来自外部api,因此我无法控制它的结构。在我的架构中,我允许所有字段都为空。
这是我的剧本
text = f"{path}/report.csv"
df = pd.read_csv(text)
row_iter = df.iterrows()
for index, row in row_iter:
rows = {key.replace("-", "_"): row.pop(key) for key in row.keys()}
# print(f"rows {rows}")
# default_values = {
# "amazon-order-id",merchant-order-id,purchase-date,last-updated-date,order-status,fulfillment-channel,sales-channel,order-channel,ship-service-level,product-name,sku,asin,item-status,quantity,currency,item-price,item-tax,shipping-price,shipping-tax,gift-wrap-price,gift-wrap-tax,item-promotion-discount,ship-promotion-discount,ship-city,ship-state,ship-postal-code,ship-country,promotion-ids,is-business-order,purchase-order-number,price-designation,is-iba,order-invoice-type
# }
sb, created = Order.objects.update_or_create(
sellingpartner_customer=c,
amazon_order_id=rows["amazon_order_id"],
sku=rows["sku"],
asin=rows["asin"],
defaults={**rows},
)但是,由于一些csv字段有空值,所以熊猫将用NaN值替换它,这就是django返回错误的地方。
django.db.utils.OperationalError: (1054, "Unknown column 'NaN' in 'field list'")我尝试将空值替换为空字符串(“”)
df.fillna("", inplace=True)但是django将返回一个非charfield字段的错误。
django.core.exceptions.ValidationError: ['“” value must be a decimal number.']我的问题是,您如何处理熊猫中csv文件中的空值,例如,如果字段类型是布尔型,那么对于django布尔型字段,只能用布尔False替换空值,对于空十进制类型,只需用0替换空值,对于空字符字段,只需用空值替换,等等。
发布于 2022-04-13 16:46:49
Nullable Django模型不会使用np.nan或其他与Pandas兼容的not-a-number对象。它期望将None作为库存Python。当您有nan值时,在将它们保存到Django之前,只需用None替换它们,以避免验证错误。
https://stackoverflow.com/questions/71860723
复制相似问题