pythondatabasesqlitepeewee

peewee.IntegrityError: NOT NULL constraint failed: user.id


''' from peewee import *

forum_db = SqliteDatabase("forum.db")

class BaseModel(Model):
    class Meta:
        database = forum_db

class User(BaseModel):
    name = CharField(unique = True)
    id = IntegerField()

class Post(BaseModel):
    id = IntegerField()
    message = TextField()
    user_id = ForeignKeyField(User, backref = "id")

class Thread(BaseModel):
    id = IntegerField()
    title = CharField()
    user_id = ForeignKeyField(User, backref = "id")
    posts = ForeignKeyField(Post)

if __name__ == "__main__":
    forum_db.connect()
    forum_db.create_tables([User, Post, Thread])

    User.create(id = 1, name = "Cameron")

'''

I am creating a database for a simple forum API that I am making. Although when I try to create a User, it gives me the error in the title. I put ''' id = 1 ''', so I am unsure how to fix this.


Solution

  • You probably want to use an auto-incrementing primary key. These are created implicitly as "id = AutoField()", but you can explicitly define one as:

    class User(...):
        id = AutoField()
    

    You have specified id = IntegerField which requires that you set the value explicitly.

    Also unrelated but your backref names are not correct. I don't think you quite understand them. They would be users in your examples.

    Please consult the beginner docs and quickstart: http://docs.peewee-orm.com/en/latest/peewee/quickstart.html#quickstart