Flask-SQLAlchemy 构造函数 [英] Flask-SQLAlchemy Constructor

查看:43
本文介绍了Flask-SQLAlchemy 构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Flask-SQLAlchemy 教程中,定义了 User 模型的构造函数:

in the Flask-SQLAlchemy tutorial, a constructor for the User model is defined:

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

对于包含两列的表,这可能是可以接受的,但是如果我有包含 10 多列的表怎么办?每次我定义一个新模型时,构造函数是否必须被定义?

for a table with two columns, that might be acceptable, but what if I have tables with 10+ columns? 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 的基础模型类(也是 SQLAlchemy 的声明性基类)定义了一个构造函数,它只接受 **kwargs 并存储给定的所有参数,因此实际上没有必要定义一个构造函数.

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

通过让基类处理 **kwargs,您可以将自己从初始化模型字段的复杂性中解放出来.

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

这篇关于Flask-SQLAlchemy 构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆