我想将数据导入到多个字段。
下面我的代码导入了数据,但只对模型应用了一个关系(不是两个,因为我在下面要求它执行两次 - 我写“cat = ...”)
在下面的示例中,我希望它从第4列和第4列导入cat(类别)。 11.我的下面的代码只对模型应用了一个类别(而不是两个)。
如何将两个字段应用于模型?我正在使用python 2.7
import csv
l = list(csv.reader(open('test_data.csv', 'rb')))
Gender_CHOICES = {
'Male': 1,
'Female': 2,
'Unisex': 3,
}
Stock_CHOICES = {
'in stock': 1,
'low stock': 2,
'out of stock': 3,
'discountinued': 4
}
for i in l[1:]:
cat = m.Category.objects.get_or_create(category_name = i[4],[11])[0]
prod = m.Product(
name = i[0],
link = i[1],
description = i[6],
brand = i[7],
colour = i[10],
gender = Gender_CHOICES[i[8]] if i[8] in Gender_CHOICES else 3,
store = m.Store.objects.get_or_create(store_name = i[2])[0]
)
prod.save()
var = m.Variation(
product = prod,
variation = "default"
)
var.save()
img = m.Image(
variation = var,
image = i[5]
)
img.save()
size = m.Size(
variation = var
)
size.save()
price = m.Price(
variation = var,
price = float(i[3])
)
price.save()
stock = m.Stock(
size = size,
stock = Stock_CHOICES[i[9]] if i[9] in Stock_CHOICES else 4
)
stock.save()
prod.category.add(cat)
CSV示例:
prod_name,prod_link,store_name,prod_price,category,image_default,prod_description,prod_brand,gender,prod_stock,category1
Bliss Firm Baby Firm Lifting & Volumising Serum 30ml - Serum,http://click.linksynergy.com/link?id=dnw*50nuNL8&offerid=287549.2554637&type=15&murl=http%3A%2F%2Fwww.asos.com%2Fau%2FBliss%2FBliss-Firm-Baby-Firm-Lifting-Volumising-Serum-30ml%2FProd%2Fpgeproduct.aspx%3Fiid%3D3936070%26istCompanyId%3Df448b47d-6b90-4b9b-a52d-eb6058c99b1c%26istItemId%3Dwxqqpxxmi%26istBid%3Dt,Asos,117,Skin Care Body Creams & Moisturisers,http://images.asos-media.com/inv/media/0/7/0/6/3936070/serum/image1xxl.jpg,Firm Baby Firm Lifting & Volumising Serum by Bliss Designed to boost collagen and elasticity Concentrated formula with a water-free aloe base Aims to plump skin from the inside out,Bliss,Female,
Yes To Carrots Day Cream 50ml - Carrots,http://click.linksynergy.com/link?id=dnw*50nuNL8&offerid=287549.2825448&type=15&murl=http%3A%2F%2Fwww.asos.com%2Fau%2FYES-TO%2FYes-To-Carrots-Day-Cream-50ml%2FProd%2Fpgeproduct.aspx%3Fiid%3D4254119%26istCompanyId%3Df448b47d-6b90-4b9b-a52d-eb6058c99b1c%26istItemId%3Dwiqwwawpm%26istBid%3Dt,Asos,21,Skin Care Body Creams & Moisturisers,http://images.asos-media.com/inv/media/9/1/1/4/4254119/carrots/image1xxl.jpg,Day cream by Yes To Carrots 95% natural ingredients Including carrots and sweet almond oil Rich moisturising formula Naturally nourishes to promote softer skin Suitable for normal to dry skin types Product size: 50ml,YES TO,Female,Belts
答案 0 :(得分:1)
我相信,问题在于对象创建。我认为您正在寻找以下内容:
....
....
for i in l[1:]:
cat_1 = m.Category.objects.get_or_create(category_name = i[4])
cat_2 = m.Category.objects.get_or_create(category_name = i[11])
....
....
prod.category.add(cat_1)
prod.category.add(cat_2)