19421608 19421608 - 9 months ago 84
Python Question

Creating SQLAlchemy model instance raises "TypeError: __init__() takes exactly 1 argument"

I have defined a model with Flask-SQLAlchemy and want to insert a row with it in a Flask view. When I try to create the instance, I get

TypeError: __init__() takes exactly 1 argument (5 given)
. I think the issue has to do with the constructor but the docs don't really explain what is required. How do I create an instance of my model while passing data to it?

class Update(db.Model):
id = db.Column(db.Integer, primary_key=True)
tracking_number = db.Column(db.Integer)
date = db.Column(db.DateTime)
status = db.Column(db.String(80))
location = db.Column(db.String(80))

def put_update():
update = Update('trackingid', '2016-08-30 22:48:00', 'status', 'location')


SQLAlchemy provides a default constructor that takes keyword arguments and assigns them to the instance.

Update(trackingnumber='trackingid', ...)

This is typically all you need, and is convenient for uses like unpacking data you get from a form (as long as the field names match up).

If you don't want to pass keywords, you can override __init__ to take whatever arguments in whatever order you want. For example, if Update always needs trackingnumber and you want to pass it as the first positional argument:

class Update(db.Model):

    def __init__(self, trackingnumber, **kwargs):
        self.trackingnumber = trackingnumber

This can be useful in some situations but typically you should just stick with the default of passing keyword arguments.