简体   繁体   English

Flask-SQLAlchemy构造函数

[英]Flask-SQLAlchemy Constructor

in the Flask-SQLAlchemy tutorial, a constructor for the User model is defined: 在Flask-SQLAlchemy教程中,定义了User模型的构造函数:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)


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, username, email):
        self.username = username
        self.email = email

for a table with two columns, that might be acceptable, but what if I have tables with 10+ columns? 对于有两列的表,这可能是可以接受的,但如果我有10列以上的表怎么办? do constructors have to be defined each time I define a new model? 每次定义新模型时必须定义构造函数吗?

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. Flask-SQLAlchemy的基本模型类(也是SQLAlchemy的声明性基类) 定义了一个构造函数 ,它只接受**kwargs并存储给定的所有参数,因此没有必要定义构造函数。

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. 通过让基类处理**kwargs您可以摆脱初始化模型字段的复杂性。

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: 如果您遇到“TypeError: init ()只需要1个参数(给定2个)” - 这意味着您需要在创建要添加到数据库的对象时提供关键字,如下所示:

db.session.add(User(username='myname',email='my@email',password='mypassword')) . 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM