1
from flask import (Flask, render_template)
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/database'
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

admin = User('admin')

This code throws TypeError: __init__() missing 1 required positional argument: 'nickname', so it seems like it expects me to manually set the id, though i probably shouldn't do it? I also tried executing User(nickname='admin'), but it doesn't seem to work. Thanks for the help

5
  • always put full error message (traceback) because there are other useful information. Commented Sep 16 at 21:51
  • you defined it as __init__(self, id, nickname): so you has to set value for id - User('some_id', 'admin'). OR remove id - __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 for self.id Commented Sep 16 at 21:51
  • 1
    do you really need to use __init__? Model should work without __init__ Commented Sep 16 at 21:58
  • eventually you could add autoincrement=True in id = db.Column(...) and it will automatically set new value. Commented Sep 16 at 22:04
  • 1
    @furas primary_key=True will handle auto-incrementing for single-column primary keys, autoincrement should be left as its default value ('auto') here. Commented Sep 17 at 7:49

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

sorry for the late response, thanks for the explanations!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.