SQLAlchemy-使用数据库列名而不是属性名在模型中设置值 [英] SQLAlchemy - set value in model using database column name, not property name
问题描述
我有一个列为TS_TEST_ID
的表.我有一个具有以下属性的SQLAlchemy模型:
I have a table with the column TS_TEST_ID
. I have a SQLAlchemy model with the following property:
id = Column(u'TS_TEST_ID', INTEGER(), primary_key=True, nullable=False)
只有已知TS_TEST_ID
时,有什么方法可以在我的模型类的实例上设置id
吗?也就是说,我只知道数据库中列的名称,并且我想以某种方式将其映射到id
并在模型上设置id
属性.我希望只执行MyModel(**{'TS_TEST_ID':1})
即可,但是出现以下错误:
Is there any way to set id
on an instance of my model class when only TS_TEST_ID
is known? That is, I only know the name of the column in the database, and I want to somehow map that to id
and set the id
property on my model. I was hoping just doing MyModel(**{'TS_TEST_ID':1})
would work, but I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 4, in __init__
File "C:\Python26\lib\site-packages\sqlalchemy\orm\state.py", line 111,
in initialize_instance
return manager.events.original_init(*mixed[1:], **kwargs)
File "C:\Python26\lib\site-packages\sqlalchemy\ext\declarative.py", line 1377,
in _declarative_constructor
(k, cls_.__name__))
TypeError: 'TS_TEST_ID' is an invalid keyword argument for MyModel
我宁愿不必为模型中的每一列都定义TS_TEST_ID = Column(u'TS_TEST_ID', INTEGER(), primary_key=True, nullable=False)
,甚至不必为返回id
属性的名为TS_TEST_ID
的方法定义.
I would rather not have to define TS_TEST_ID = Column(u'TS_TEST_ID', INTEGER(), primary_key=True, nullable=False)
for every column in my model, either, or even a method called TS_TEST_ID
that returns the id
property.
推荐答案
这似乎比需要的要复杂,但可以.我希望有一种更直接的方法...
This seems more complicated than it needs to be, but it works. I'm hoping there's a more direct way of doing this...
@staticmethod
def fromFieldHash(h):
row = MyModel()
cols = list(row.__table__._columns)
for k, v in h.iteritems():
col = find(lambda c: c.key == k, cols)
# See http://www.sqlalchemy.org/trac/wiki/06Migration#AnImportantExpressionLanguageGotcha
if col is not None:
prop = row.__mapper__._columntoproperty[col].key
setattr(row, prop, v)
return row
我正在使用的find
方法来自最干净的Python查找-in-list功能.
The find
method I'm using is from Cleanest Python find-in-list function.
这篇关于SQLAlchemy-使用数据库列名而不是属性名在模型中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!