Model.from_dict(obj_dict) method?

280 views
Skip to first unread message

Kyle Finley

unread,
Feb 7, 2012, 10:36:15 AM2/7/12
to appengine-...@googlegroups.com
I often find myself needing to convert a dictionary into a ndb Model / StructuredProperty. Has anyone written a method for doing so? Or are there limitations that make this difficult.

m = MyModel.get_by_id('123')
m_dict = m.to_dict()
m_model = MyModel.from_dict(m_dict)

self.assertEqual(m, m_model)


Thanks,


Kyle

Guido van Rossum

unread,
Feb 7, 2012, 11:06:10 AM2/7/12
to appengine-...@googlegroups.com

You can use MyModel(**m_dict), or the following:

m2 = MyModel()
m2.populate(**m_dict)

--
--Guido van Rossum (python.org/~guido)

Kyle Finley

unread,
Feb 7, 2012, 11:54:02 AM2/7/12
to appengine-...@googlegroups.com
Thanks, Guido.

The problem that I was having was that those two methods didn't work with ndb.StructuredProperty or ndb.LocalStructuredProperty.

BadValueError: Expected ModelClass instance

I believe this can be over come by utilizing the prop._modelclass, I just want to see if anyone else had written this method, before I looked into it more deeply.

- Kyle

Guido van Rossum

unread,
Feb 7, 2012, 12:56:23 PM2/7/12
to appengine-...@googlegroups.com
On Tue, Feb 7, 2012 at 08:54, Kyle Finley <kylef...@gmail.com> wrote:
>
> Thanks, Guido.
>
> The problem that I was having was that those two methods didn't work with ndb.StructuredProperty or ndb.LocalStructuredProperty.

That wasn't clear from your post -- while you mentioned
StructuredProperty it didn't occur in your code sample.

> BadValueError: Expected ModelClass instance

This is because to_dict() returns a dict for [Local]StructuredProperty
instead of a Model instance, but the constructor and .propagate()
require Model instances for those.

> I believe this can be over come by utilizing the prop._modelclass, I just want to see if anyone else had written this method, before I looked into it more deeply.

You have presented a use case for from_dict() class method... I've
added a feature request for this to the tracker:
http://code.google.com/p/appengine-ndb-experiment/issues/detail?id=147

--Guido

Reply all
Reply to author
Forward
0 new messages