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

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

问题描述

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

  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 =用户名
self.email =电子邮件

表中有两列,这可能是可以接受的,但如果我有10列以上的表呢?每次我定义一个新的模型时,是否有构造函数

解决方案

在大多数情况下,在模型类中没有定义构造函数会给你正确的行为。
Flask-SQLAlchemy的基本模型类(也是SQLAlchemy的声明性基类)定义了一个构造函数,它只需要 ** kwargs 并存储所有给定的参数,所以它没有必要定义一个构造函数。

如果你确实需要定义一个构造函数来做一些模型特定的初始化操作,那么这样做如下: / b>

  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)
#在这里自定义初始化

通过让基类处理 ** kwargs ,您可以释放自己的fr ü初始化模型的字段的复杂性。


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

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'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.

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

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