django.db.utils.IntegrityError: (1048, "Column 'spu_id' cannot be null")关于RESTframework使用序列化器报错问题
ERROR exception 132 Internal Server Error: /meiduo_admin/goods/specs/ Traceback (most recent call last): File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\cursors.py", line 170, in execute result = self._query(query) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\cursors.py", line 328, in _query conn.query(q) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 732, in _read_query_result result.read() File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 1075, in read first_packet = self.connection._read_packet() File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 684, in _read_packet packet.check_error() File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1048, "Column 'spu_id' cannot be null") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\python_learn\meiduo_project\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\viewsets.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\views.py", line 483, in dispatch response = self.handle_exception(exc) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\mixins.py", line 21, in create self.perform_create(serializer) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\mixins.py", line 26, in perform_create serializer.save() File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\serializers.py", line 214, in save self.instance = self.create(validated_data) File "D:\python_learn\meiduo_project\env\lib\site-packages\rest_framework\serializers.py", line 940, in create instance = ModelClass.objects.create(**validated_data) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\base.py", line 807, in save self.save_base(using=using, force_insert=force_insert, File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\base.py", line 924, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\base.py", line 962, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\models\sql\compiler.py", line 1112, in execute_sql cursor.execute(sql, params) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "D:\python_learn\meiduo_project\env\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\cursors.py", line 170, in execute result = self._query(query) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\cursors.py", line 328, in _query conn.query(q) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 732, in _read_query_result result.read() File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 1075, in read first_packet = self.connection._read_packet() File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\connections.py", line 684, in _read_packet packet.check_error() File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "D:\python_learn\meiduo_project\env\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) django.db.utils.IntegrityError: (1048, "Column 'spu_id' cannot be null") ERROR basehttp 124 "POST /meiduo_admin/goods/specs/ HTTP/1.1" 500 28792
1.根据提示一开始查询是否是前端请求数据有误:
发现没有错误,返回的request.data中有spu_id和name值
2.但是报错显示
"Column 'spu_id' cannot be null",且是pymysql在保存过程中出现错误,所以可能是因为在serializer序列化器中的没有定义spu_id的属性;
原来的序列化是代码如下:
class SPUSpecsViewSerializer(serializers.ModelSerializer): spu = serializers.StringRelatedField(read_only=True) class Meta: model = SPUSpecification fields = ('id', 'name', 'spu_id', 'spu')
3.但是在models模型类中查看,发现原来模型类对象并不处在spu_id字段
class SPUSpecification(BaseModel): """商品SPU规格""" spu = models.ForeignKey(SPU, on_delete=models.CASCADE, related_name='specs', verbose_name='商品SPU') name = models.CharField(max_length=20, verbose_name='规格名称') class Meta: db_table = 'tb_spu_specification' verbose_name = '商品SPU规格' verbose_name_plural = verbose_name def __str__(self): return '%s: %s' % (self.spu.name, self.name)
4.所以推测可能是因为在序列化器中未定义spu_id字段,所以无法和表中信息相对应,所以在序列化器中加入spu_id的定义:
class SPUSpecsViewSerializer(serializers.ModelSerializer): spu = serializers.StringRelatedField(read_only=True) spu_id = serializers.IntegerField() class Meta: model = SPUSpecification fields = ('id', 'name', 'spu_id', 'spu')
5.问题解决
壬戌之秋,七月既望,苏子与客泛舟游于赤壁之下。清风徐来,水波不兴。举酒属客,诵明月之诗,歌窈窕之章。少焉,月出于东山之上,徘徊于斗牛之间。白露横江,水光接天。纵一苇之所如,凌万顷之茫然。浩浩乎如冯虚御风,而不知其所止;飘飘乎如遗世独立,羽化而登仙。
于是饮酒乐甚,扣舷而歌之。歌曰:“桂棹兮兰桨,击空明兮溯流光。渺渺兮予怀,望美人兮天一方。”客有吹洞箫者,倚歌而和之。其声呜呜然,如怨如慕,如泣如诉,余音袅袅,不绝如缕。舞幽壑之潜蛟,泣孤舟之嫠妇。
苏子愀然,正襟危坐而问客曰:“何为其然也?”客曰:“月明星稀,乌鹊南飞,此非曹孟德之诗乎?西望夏口,东望武昌,山川相缪,郁乎苍苍,此非孟德之困于周郎者乎?方其破荆州,下江陵,顺流而东也,舳舻千里,旌旗蔽空,酾酒临江,横槊赋诗,固一世之雄也,而今安在哉?况吾与子渔樵于江渚之上,侣鱼虾而友麋鹿,驾一叶之扁舟,举匏樽以相属。寄蜉蝣于天地,渺沧海之一粟。哀吾生之须臾,羡长江之无穷。挟飞仙以遨游,抱明月而长终。知不可乎骤得,托遗响于悲风。”
苏子曰:“客亦知夫水与月乎?逝者如斯,而未尝往也;盈虚者如彼,而卒莫消长也。盖将自其变者而观之,则天地曾不能以一瞬;自其不变者而观之,则物与我皆无尽也,而又何羡乎!且夫天地之间,物各有主,苟非吾之所有,虽一毫而莫取。惟江上之清风,与山间之明月,耳得之而为声,目遇之而成色,取之无禁,用之不竭,是造物者之无尽藏也,而吾与子之所共适。”
客喜而笑,洗盏更酌。肴核既尽,杯盘狼籍。相与枕藉乎舟中,不知东方之既白。