Reputation: 3183
I have an ORM mapped object, that I want to update. I have all attributes validated and secured in a dictionary (keyword arguments). Now I would like to update all object attributes as in the dictionary.
for k,v in kw.items():
setattr(myobject, k, v)
doesnt work (AttributeError Exception), thrown from SQLAlchemy.
myobject.attr1 = kw['attr1']
myobject.attr2 = kw['attr2']
myobject.attr3 = kw['attr3']
etc is horrible copy paste code, I want to avoid that.#
How can i achieve this? SQLAlchemy already does something similar to what I want to do in their constructors ( myobject = MyClass(**kw) ), but I cant find that in all the meta programming obfuscated crap in there.
error from SA:
<< if self.trackparent:
if value is not None:
self.sethasparent(instance_state(value), True)
if previous is not value and previous is not None:
self.sethasparent(instance_state(previous), False)
>> self.sethasparent(instance_state(value), True)
AttributeError: 'unicode' object has no attribute '_sa_instance_state'
Upvotes: 1
Views: 1166
Reputation: 54910
You are trying to assign a unicode string to a relation attribute. Say you have:
class ClassA(Base):
...
b_id = Column(None, ForeignKey('b.id'))
b = relation(ClassB)
And you are trying to do:
my_object = ClassA()
my_object.b = "foo"
When you should be doing either:
my_object.b_id = "foo"
# or
my_object.b = session.query(ClassB).get("foo")
Upvotes: 3