I don't know why you use __init__
at all. It will work without it
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(80), unique=True)
# --- create tables in database ---
with app.app_context():
db.create_all()
# --- create User, save it in database, get ID ---
with app.app_context():
admin = User(nickname='admin')
print('before:', admin.nickname, admin.id)
db.session.add(admin)
db.session.commit()
print(' after:', admin.nickname, admin.id)
Full working code for SQLite so everyone could run it:
from flask import (Flask, render_template)
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/database'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.sqlite'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(80), unique=True)
# def __init__(self, id, nickname):
# self.id = id
# self.nickname = nickname
# --- create tables in database ---
with app.app_context():
db.create_all()
# --- get unique name from command line ---
import sys
if len(sys.argv) > 1:
name = sys.argv[1]
else:
name = 'admin'
# --- create User, save it in database, get ID ---
with app.app_context():
admin = User(nickname=name)
print('before:', admin.nickname, admin.id)
db.session.add(admin)
db.session.commit()
print(' after:', admin.nickname, admin.id)
# --- show list of Users ---
with app.app_context():
for user in db.session.execute(db.select(User)).all():
user = user[0]
print(user.id, user.nickname)
__init__(self, id, nickname):
so you has to set value forid
-User('some_id', 'admin')
. OR removeid
-__init__(self, nickname)
. Or put at the end with default value__init__(self, nickname, id=None)
. But in last two versions you have to add code which set value forself.id
__init__
? Model should work without__init__
autoincrement=True
inid = db.Column(...)
and it will automatically set new value.primary_key=True
will handle auto-incrementing for single-column primary keys, autoincrement should be left as its default value ('auto') here.