我尝试根据topCategory和middleCategory的外键主键保存项目。
models.py
class MiddleCategory(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
def __str__(self):
return self.title
class TopCategory(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
middleCategory = models.ManyToManyField(MiddleCategory)
def __str__(self):
return self.title
# Item
class Product(models.Model):
title = models.CharField(max_length=500, db_index=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
brand = models.CharField(max_length=100)
# brand_id = models.IntegerField()
retailer = models.CharField(max_length=255)
image = models.CharField(max_length=1000)
url = models.URLField(max_length=800, unique=True, default='')
model_numbers = models.BigIntegerField(default=0)
description = models.CharField(max_length=500)
featured = models.CharField(max_length=255, db_index=True, default='NO')
timestamp = models.DateTimeField(auto_now=True)
topCategory = models.ForeignKey(TopCategory)
middleCategory = models.ForeignKey(MiddleCategory)
def __str__(self):
return self.title
在我的剧本中,我这样保存:
Product(title=title,
price=price,
brand=brand,
retailer=retailer,
image=image,
url=url,
description=description,
midCategory=midCategory,
topCategory=topCategory
).save()
这是我得到的错误:
ValueError:无法分配"' 1'":" Product.topCategory"必须是" TopCategory"实例
答案 0 :(得分:1)
您可以获取TopCategory的实例
instance = TopCategory.objects.get(id=topCategory)
然后
Product(title=title,
price=price,
brand=brand,
retailer=retailer,
image=image,
url=url,
description=description,
midCategory=midCategory,
topCategory=instance
).save()