python - Adding __init__() method in Flask-SQLAlchemy
问题描述
I'm using Flask-SQLAlchemy in python 3.6.5 and -- so far -- have not been able to extend a model with a call to __init__()
. My code looks like this:
'''
file: models.py
'''
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Network(db.Model):
__tablename__ = 'network'
id = db.Column(db.Integer, primary_key=True)
baud_rate = db.Column(db.Integer)
def __init__(**kwargs):
super(Network, self).__init__(**kwargs) # see note
Attempting to instantiate a Network object results in an error:
>>> n = Network(baud_rate=300)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __init__() takes 0 positional arguments but 1 was given
This is a bit surprising, since I'm using the recipe given in the Flask-SQLAlchemy documentation:
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:
class Foo(db.Model): # ... def __init__(**kwargs): super(Foo, self).__init__(**kwargs) # do custom stuff
Since I'm using python 3.6, I thought maybe I should upgrade the call to super()
, as in :
def __init__(**kwargs):
super().__init__(**kwargs)
... but that didn't make any difference.
解决方案
听起来文档忘记在(A pull request was accepted in may)中提及该self
属性:__init__
class Network(db.Model):
__tablename__ = 'network'
id = db.Column(db.Integer, primary_key=True)
baud_rate = db.Column(db.Integer)
def __init__(self, **kwargs):
super().__init__(**kwargs)
推荐阅读
- swift - 解决多个数据库问题
- dialogflow-cx - DialogFlow CX 与 SQL Server 集成
- sql - 通过sql上的链接计数不同?
- javascript - 如何防止不同“导航”的竞争条件?
- google-chrome - 网站在 Mozilla 中可以正常打开,但在 chrome 中不能正常打开
- javascript - 如何在 JavaScript 中不同时获得我想要的所有颜色
- fairseq - 在内存和预加载语言模型中运行 Fairseq
- java - 如何从弹性搜索中具有数组值的字段中获得相等匹配的结果
- r - 根据另一个用R中的二进制状态填充数据帧
- typescript - 类的类型提示作为 TypeScript 中的参数