创建SQLAlchemy模型实例引发“TypeError:__init __()只需要1个参数” [英] Creating SQLAlchemy model instance raises "TypeError: __init__() takes exactly 1 argument"
问题描述
我用Flask-SQLAlchemy定义了一个模型,并想在Flask视图中插入一行。当我尝试创建实例时,得到 TypeError:__init __()只需要1个参数(给定5)
。我认为这个问题与构造函数有关,但文档并没有真正解释需要什么。如何在传递数据的同时创建我的模型实例?
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))
@app.route('/put_update')
def put_update():
update = Update('trackingid', '2016-08-30 22:48:00', 'status', 'location')
db.session.add(update)
db.session.commit()
推荐答案
SQLAlchemy提供了一个默认的构造函数,它接受关键字参数并将它们分配给实例。
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).
如果您不想传递关键字,可以覆盖 __ init __
,以您想要的任何顺序接受任何参数。例如,如果 Update
总是需要 trackingnumber
,并且您想将其作为第一个位置参数传递:
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
super().__init__(**kwargs)
在某些情况下,这可能很有用,但通常您应该坚持使用传递关键字参数的默认值。
This can be useful in some situations but typically you should just stick with the default of passing keyword arguments.
这篇关于创建SQLAlchemy模型实例引发“TypeError:__init __()只需要1个参数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!