首页 > 解决方案 > 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.

标签: pythonpython-3.xflaskflask-sqlalchemy

解决方案


听起来文档忘记在(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)

推荐阅读