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)
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
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...
The
find
method I'm using is from Cleanest Python find-in-list function.If one would like
__init__
to handle both attributes and columns, though having a dedicatedclassmethod
factory seems like a cleaner approach, the following implementation could be used as an abstract base:Using the above the following asserts pass: