A follow up, more dict to SqlAlchemy fun
03Apr10
Just a quick follow up to my last post on adding the ability to add some tools to help serialize SqlAlchemy instances. I needed to do the reverse. I want to take the POST’d values from a form submission and tack them onto one of my models. So I now also add a fromdict() method onto base that looks like.
def fromdict(self, values):
"""Merge in items in the values dict into our object if it's one of our columns
"""
for c in self.__table__.columns:
if c.name in values:
setattr(self, c.name, values[c.name])
Base.fromdict = fromdict
So in my controllers I can start doing
def controller(self):
obj = SomeObj()
obj.fromdict(request.POST)
Session.add(obj)
Filed under: Tech, Uncategorized | 2 Comments
Tags: python, sqlalchemy

Does this work with the datetime conversion also? (You mentioned you had a problem with datetime conversion in your earlier post)
02 def convert_datetime(value):
03 return value.strftime(“%Y-%m-%d %H:%M:%S”)
Yes, this works for datetime because SqlAlchemy will auto handle the date conversion. My earilier problem was that I needed to get something that could be JSON’d and the datetime models didn’t work right. They needed to be string-ified first.