Flask-SQLAlchemy - TypeError: __init__() takes only 1 position

拈花ヽ惹草 提交于 2020-01-15 08:20:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!