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)



2 Responses to “A follow up, more dict to SqlAlchemy fun”

  1. 1 Hal

    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”)

  2. 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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.