fearless_fool
fearless_fool

Reputation: 35169

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.

Upvotes: 4

Views: 4205

Answers (1)

PRMoureu
PRMoureu

Reputation: 13327

Sounds like the doc forgets to mention the self attribute in __init__ (A pull request was accepted in may) :

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)

Upvotes: 6

Related Questions