我有以下型号:
class Vendor(models.Model):
name = models.CharField(max_length=50, unique=True)
seo_name = models.SlugField()
def __str__(self):
return self.name
class Product(models.Model):
vendor = models.ForeignKey(Vendor, unique=False, blank=True, default=None, null=True, on_delete=models.SET_NULL)
我制作xml文件的解析器并在这些文件供应商设置的foreach位置,我只需要在供应商模型中保存唯一值,但对于每个产品集他的供应商,我这样做:
for p in products:
vendor = Vendor()
vendor.name = p['vendor']
try:
vendor.save()
except:
pass
product.vendor = vendor
结果是,在解析其供应商尚未保存时,仅在分配给这些值的产品供应商的模型中。 问题是如何确保将供应商分配给每个产品?
产品中cicle p的所有代码:
def adversolution_aizel(xml_file):
e = ET.parse(xml_file)
d = etree_to_dict(e.getroot())
shop_name = d['yml_catalog']['shop']['name']
shop_company = d['yml_catalog']['shop']['company']
shop_url = d['yml_catalog']['shop']['url']
shop_attr = Shop()
shop_attr.name = shop_name
shop_attr.seo_name = shop_company
shop_attr.import_url = shop_url
try:
shop_attr.save()
except:
pass
products = d['yml_catalog']['shop']['offers']['offer']
for p in products:
product = Product()
product.external_url = p['url']
product.price = p['price']
product.old_price = p['oldprice']
product.currencies = p['currencyId']
# product.category_id = p['categoryId']
#############################################################################
picture = Image()
picture.external_img_url = p['picture']
picture.save()
product.picture = picture
##############################################################################
product.name = p['name']
##############################################################################
vendor = Vendor()
vendor.name = p['vendor']
try:
vendor.save()
except:
pass
product.vendor = vendor
##############################################################################
product.shop = shop_name
product.description = p['description']
product.save()