Flask-SQLAlchemy Constructor

让人想犯罪 __ 提交于 2019-11-28 04:23:52
Miguel

In most cases not defining a constructor in your model class gives you the correct behavior.

Flask-SQLAlchemy's base model class (which is also SQLAlchemy's declarative base class) defines a constructor that just takes **kwargs and stores all the arguments given, so it isn't really necessary to define a constructor.

If you do need to define a constructor to do some model specific initialization, then do so as follows:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        # do custom initialization here

By letting the base class handle the **kwargs you free yourself from the complexity of initializing the fields of the model.

I know this is a little old but regardless it should be useful for someone else with similar issue. If you encounter the "TypeError: init() takes exactly 1 argument (2 given)" - it means you need to provide the keywords when creating the objects to add to your database like so:

db.session.add(User(username='myname',email='my@email',password='mypassword')).

It is quite common to come across this small issue...but difficult to spot. I hope this helps.

You can write the constructor however you want, you'll just need to initialize each field before trying to save the object in the database.

class User(db.Model):
    ...

user = User()
user.username = 'foo'
user.email = 'foo@bar.com'
db.session.add(user)

You can initialize parameters in the constructor this way as well.

class User(db.Model):
    ...
    def __init__(self, username, email):
        self.username = username
        self.email = email
        self.password = generate_random_password()
        self.last_login = None
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!