Not null constraint failed ошибка

coldmind’s answer is correct but lacks details.

The NOT NULL constraint failed occurs when something tries to set None to the zipcode property, while it has not been explicitly allowed.

It usually happens when:

  1. Your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).

    For instance, if somewhere in your code an assignment results in:

    model.zipcode = None
    

    This error is raised.

  2. When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven’t defined any. So this error can not only happen during code execution but also when creating the database?

  3. Note that the same error would be returned if you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be an automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456

    So you’ll have to define the field by one of the following:

    models.IntegerField(_('zipcode'), max_length=5, Null=True,
       blank=True)
    
    models.IntegerField(_('zipcode'), max_length=5, Null=False,
       blank=True, default=00000)
    
    models.IntegerField(_('zipcode'), max_length=5, blank=True,
       default=00000)
    

    and then make a migration (python3 manage.py makemigration <app_name>) and then migrate (python3 manage.py migrate).

    For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:

    <NUMBER>_auto_<DATE>_<HOUR>.py
    

Finally, if you don’t set Null=True, make sure that mode.zipcode = None is never done anywhere.

coldmind’s answer is correct but lacks details.

The NOT NULL constraint failed occurs when something tries to set None to the zipcode property, while it has not been explicitly allowed.

It usually happens when:

  1. Your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).

    For instance, if somewhere in your code an assignment results in:

    model.zipcode = None
    

    This error is raised.

  2. When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven’t defined any. So this error can not only happen during code execution but also when creating the database?

  3. Note that the same error would be returned if you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be an automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456

    So you’ll have to define the field by one of the following:

    models.IntegerField(_('zipcode'), max_length=5, Null=True,
       blank=True)
    
    models.IntegerField(_('zipcode'), max_length=5, Null=False,
       blank=True, default=00000)
    
    models.IntegerField(_('zipcode'), max_length=5, blank=True,
       default=00000)
    

    and then make a migration (python3 manage.py makemigration <app_name>) and then migrate (python3 manage.py migrate).

    For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:

    <NUMBER>_auto_<DATE>_<HOUR>.py
    

Finally, if you don’t set Null=True, make sure that mode.zipcode = None is never done anywhere.

from RXConfigBase import bot, logger
from RXSQLConfig import sqlite3, user_id, name, surname, patronymic


#Начало, логиниться и регистрация
@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.from_user.id,  'Добро пожаловать!\n' f'‍♂️>> {message.chat.first_name}|{message.chat.last_name} <<‍♀️\n\n' 'Входа в систему /log\n' 'Регистрация /reg')

#Регистрация
@bot.message_handler(commands=['reg'])
def start_message(message):
    bot.send_message(message.from_user.id, 'Регистрацию аккаунта.\nНачнём?(Напиши "next")')
    bot.register_next_step_handler(message, name)

#Собираем данные для регистрации и БД
def name(message): #получаем имя
    bot.send_message(message.from_user.id, 'Укажите имя')
    global name
    global user_id
    user_id = message.from_user.id
    name = message.text
    conn = sqlite3.connect("DataBase/RXDataBase.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Profile (user_id, name) VALUES (?, ?)", (user_id, name, ))
    #cursor.execute(f"SELECT get_user_id FROM Profile WHERE id = {message.from_user.id}")
    #cursor.execute(f"SELECT get_name FROM Profile WHERE id = {message.text}")
    bot.register_next_step_handler(message, surname)

def surname(message): #получаем фамилии
    bot.send_message(message.from_user.id, 'Укажите фамилию')
    global surname
    surname = message.text
    conn = sqlite3.connect("DataBase/RXDataBase.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Profile (surname) VALUES (?)", (surname, ))
    bot.register_next_step_handler(message, patronymic)

def patronymic(message): #получаем отчества
    bot.send_message(message.from_user.id, 'Укажите отчество')
    global patronymic
    patronymic = message.text
    conn = sqlite3.connect("DataBase/RXDataBase.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Profile (patronymic) VALUES (?)", (patronymic, ))
    return




if __name__ == '__main__':
    bot.polling(none_stop=True, interval=0)

Ошибка:
cursor.execute(«INSERT INTO Profile (user_id, name) VALUES (?, ?)», (user_id, name))
sqlite3.IntegrityError: NOT NULL constraint failed: Profile.surname

Django Forum

Loading

Hello,

We are struggling for this almost whole day and we don’t see where is the problem. Everything seems good but we realized that somehow after second connection to database and calling different queries we loose PRIMARY KEY at files table.

Here is what we have and what we call to get error Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: files.id

user.entity.ts

import { Entity } from 'typeorm/decorator/entity/Entity';
import {Column, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import {Sources} from './sources.entity';

@Entity()
export class Users {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column("varchar", { nullable: true})
  email: string;

  @OneToMany(type => Sources, source => source.user, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: true
  })
  source: Sources[];
}

source_type.entity.ts


import {Entity} from 'typeorm/decorator/entity/Entity';
import {Column, OneToOne, PrimaryGeneratedColumn} from 'typeorm';
import { Sources } from './sources.entity';

@Entity()
export class SourceType {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(type => Sources, sourcesType => sourcesType.sourceType, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: true
  })
  source: Sources;
}

sources.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import {Column, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn} from 'typeorm';
import { SourceType } from './source_type.entity';
import { Users } from './user.entity';
import {SourcesPaths} from "./sources_paths.entity";
import {Files} from "./files.entity";

@Entity()
export class Sources {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(type => SourceType)
  @JoinColumn()
  sourceType: SourceType;

  @ManyToOne(type => Users, users => users.source)
  @JoinColumn()
  user: Users;

  @OneToMany(type => SourcesPaths, sourcesPaths => sourcesPaths.source)
  sourcePath: SourcesPaths[];

  @OneToMany(type => Files, file => file.source)
  file: Files[];

}

files.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import { Column, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn } from 'typeorm';
import {Sources} from './sources.entity';
import {FilesTags} from './files_tags.entity';

@Entity()
export class Files {

  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar', {length: 45})
  name: string;

  @Column('varchar', {length: 45, nullable: true})
  family_name: string;

  @Column('varchar', {length: 45, nullable: true})
  created_at: string;

  @ManyToOne(type => Sources, source => source.file)
  @JoinColumn()
  source: Sources;

  @OneToMany(type => FilesTags, fileTag => fileTag.file)
  fileTag: FilesTags[];
}

insertUser function
When we call insert function for the first time everything goes well. Data is inserted including data into files entity also. But on second call to insertUser() we are getting error
Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: files.id

In SQLite studio we saw that after first insert of files we loose primary key on files.id.
Are we doing something wrong or there is an issue in typeorm?

insertUser(): void {

    createConnection({

      type: 'sqlite',
      database: '../user.sqlite',
      entities: [
        Users,
        Sources,
        SourceType,
        Files
      ],
      autoSchemaSync: true,
    }).then( async connection => {

      // Here you can start to work with your entities
      const user = new Users();
      user.name = 'Mezenga1234';

     await connection.manager.save(user);

      const sourcetype = new SourceType();
      sourcetype.name = 'my_library';
     await connection.manager.save(sourcetype);

      const source = new Sources();
      source.name = 'my_source';
      source.sourceType = sourcetype;
      source.user = user;

     await connection.manager.save(source);

      const files = new Files();
      files.name = 'Haris.rvt';
      files.source = source;

      await connection.manager.save(files);

      console.log('Inserted');
      connection.close();

    }).catch(error => console.log(error));

  }

Понравилась статья? Поделить с друзьями:
  • Nox player ошибка при синтаксическом анализе пакета
  • Not mpisp mode 1b ssd ошибка
  • Nox app player ошибка при запуске приложения
  • Not kwp1281 protocol ошибка
  • Norton ошибка 3039