问题
I just want to create and test db with flask-sqlalchemy. DB created yet succesfuly. My code:
class Entry(db.Model):
id = db.Column(db.Integer, primary_key=True)
occurences = db.Column(db.String(80), unique=True)
a = Entry('run.py:27')
Error:
a = Entry('run.py:27')
TypeError: __init__() takes 1 positional argument but 2 were given
If I trying to do this without arguments program returns this:
qlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: entry [SQL: 'INSERT INTO entry (occurences) VALUES (?)'] [parameters: (None,)]
error starts on line with
db.session.commit()
回答1:
You have to define the __init__
method to support the model fields:
class Entry(db.Model):
id = db.Column(db.Integer, primary_key=True)
occurences = db.Column(db.String(80), unique=True)
def __init__(self, occurences):
self.occurences = occurences
回答2:
According to their docs:
SQLAlchemy adds an implicit constructor to all model classes which accepts keyword arguments for all its columns and relationships. If you decide to override the constructor for any reason, make sure to keep accepting **kwargs and call the super constructor with those **kwargs to preserve this behavior...
Meaning your code failed because the constructor expects keyword arguments. You could fix it by:
# instantiating Entry with the occurences keyword
a = Entry(occurences='run.py:27')
or overriding the __init__
...in which case you should also include a **kwargs
and a call to super.
来源:https://stackoverflow.com/questions/37166492/flask-sqlalchemy-typeerror-init-takes-only-1-position