Search code examples
peewee

how to prevent inserting NULL values and raising exception instead


After running this code, the data will be inserted into the database. when I check the database, I find a row added with values: int_field=0 and other="" (empty string)

My question is how to throw exception in case of Null/empty insert.

from datetime import datetime

db = pw.MySQLDatabase('tests', user = 'root', password = 'root', host = 'localhost', port = 3306)

class Model(pw.Model):
name = pw.CharField()
created_at = pw.DateTimeField(default = datetime.now())
other = pw.CharField(null = False)
int_field = pw.IntegerField(null = False)

class Meta:
    database = db
    db_table = 'nmodel'
Model.create_table()
Model.create(name = "tests")

Solution

  • Its a MySQL strict_mode issue, you should enable it in peewee Database Instance Like below.

    Add this (sql_mode='STRICT_ALL_TABLES') to the constrcutor call:

    db=pw.MySQLDatabase('database_name', user='user_name', password='user_psswd',
                                  host='host_name', port=port_num,sql_mode='STRICT_ALL_TABLES') 
    

    This will throw a mysql exception when null values are passed.