django.db.utils.IntegrityError:(1048," Column' category_type'不能为null")

时间:2018-01-30 17:07:54

标签: python django

goods.py

class Goods(models.Model):
    category = models.ForeignKey(GoodsCategory, verbose_name='xxx')
    goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx')
    name = models.CharField(max_length=300, verbose_name='xxx')
    click_num = models.IntegerField(default=0, verbose_name='xxx')
    sold_num = models.IntegerField(default=0, verbose_name='xxx')

GoodsCategory.py

class GoodsCategory(models.Model):
    CATEGORY_TYPE = (
        (1, "Level 1"),
        (2, "Level 2"),
        (3, "Level 3"),
    )
    name = models.CharField(default="", max_length=30, verbose_name="Category name", help_text="Category name")
    code = models.CharField(default="", max_length=30)
    desc = models.TextField(default="", verbose_name="describe")
    category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="Category Level", help_text="Category Leve")
    parent_category = models.ForeignKey("self", null=True, blank=True, related_name="sub_cat")
    is_tab = models.BooleanField(default=False)
    add_time = models.DateTimeField(default=datetime.now)

import_goods_data.py

for goods_detail in row_data:
    goods = Goods()
    goods.name = goods_detail["name"]
    goods.market_price = float(int(goods_detail["market_price"].replace("¥", "").replace("$", "")))
    goods.shop_price = float(int(goods_detail["sale_price"].replace("¥", "").replace("$", "")))
    goods.goods_brief = goods_detail["desc"] if goods_detail["desc"] is not None else ""
    goods.goods_desc = goods_detail["goods_desc"] if goods_detail["goods_desc"] is not None else ""
    goods.goods_front_image = goods_detail["images"][0] if goods_detail["images"] else ""
    category_name = goods_detail["categorys"][-1]
    categories = GoodsCategory.objects.filter(name=category_name) 
    if categories.exists():
        category = categories[0]
    else:
        category = GoodsCategory.objects.create(name=category_name)
    goods.category = category
    goods.save()

当我运行此脚本将本地数据导入mysql时,我收到此错误:

django.db.utils.IntegrityError: (1048, "Column 'category_type' cannot be null")

我已经尝试了很多次但仍然没有解决这个问题。你能救我吗?

1 个答案:

答案 0 :(得分:0)

创建新的GoodsCategory时,您需要明确设置category_type,在模型中设置default值或将字段设置为可为空(null=True)。 glibc source