Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 964
fearless_fool Avatar asked Oct 18 '25 10:10

fearless_fool


1 Answers

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)
like image 117
PRMoureu Avatar answered Oct 21 '25 01:10

PRMoureu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!