django.db.utils.IntegrityError:(1048,“列'category_id'不能为空”)?

时间:2017-10-24 13:32:41

标签: 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')

import_goods_data.py

from apps.goods.models import Goods, GoodsCategory, GoodsImage

from db_tools.data.product_data import row_data

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'] is not None else ''

    category_name = goods_detail['categorys'][-1]
    category = GoodsCategory.objects.filter(name=category_name)
    if category:
        goods.category = category[0]
    goods.save()
goods.py中的

,而不是'category_id',为什么运行'import_goods_data.py'会收到错误:

_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1048, "Column 'category_id' cannot be null")

并且必须添加'category_id'?

1 个答案:

答案 0 :(得分:0)

问题是category是必填字段,但如果不存在具有该名称的类别,则不会设置goods.category

你如何处理这取决于你。如果不存在,也许您想创建该类别:

categories = GoodsCategory.objects.filter(name=category_name)
if categories.exist():
    category = categories[0]
else:
    category = GoodsCategory.objects.create(name=category_name)
goods.category = category[0]

如果name字段是唯一的,您可以使用get_or_create简化代码。

category, created = GoodsCategory.objects.get_or_create(name=category_name)
goods.category = category