Convert dictionaries to django model (recursively)

2,398 views
Skip to first unread message

Jacco77

unread,
Aug 15, 2011, 12:11:32 PM8/15/11
to Django users
Hi,

I want build a custom api (have tried and abandoned tastypie and
restframework). I have come to the the point where I want to save a
dictionary in a django model.

Example:

class Person(models.Model):
name = models.CharField()
title = models.CharField()
class Log(models.Model):
person = models.ForeignKey(Person)
action = models.CharField()
time = models.DateTimeField()


I have a dictionary, and would like it to be saved to database

d = {
'person':{'name':'Joe', 'title':'Boss'},
'action':'Got to work',
'time':'2011-01-01 14:00'
}

if I do:
Log(**d)

I get error message:
Cannot assign "'person':{'name':'Joe', 'title':'Boss'}": "Log.person"
must be a "Person" instance.

How can I get django to understand that I want it to convert my
dictionary recursively? Then I want to full save it (the whole blob)
recursively, that is fields that are pointing to other models should
be saved first.


Thanks in advance

David


Landy Chapman

unread,
Aug 15, 2011, 7:24:20 PM8/15/11
to Django users

Masklinn

unread,
Aug 16, 2011, 5:49:15 AM8/16/11
to django...@googlegroups.com
On 2011-08-15, at 18:11 , Jacco77 wrote:
>
> How can I get django to understand that I want it to convert my
> dictionary recursively? Then I want to full save it (the whole blob)
> recursively, that is fields that are pointing to other models should
> be saved first.
The only piece of Django I can think of which would do that sort of
things is the serialization framework.

While it does not (as far as I know) expose any interface to
serializing objects as Python dicts and arrays, it does support
serializing to JSON (although the structure is a bit more complex
than what you show here as it stores the instance's model at a
higher level of the structure than the raw field values), it should
be a good start towards vivifying simple dicts into complete object
structures.

Therefore, I would recommend looking into serializers and how they're
coded, and maybe just rework your dict structure a bit and add a new
serializer to/from python dicts (I'm not sure how pluggable django's
serializers are, but considering there's a SERIALIZATION_MODULES[0]
settings key I'm guessing you can add pretty much anything you want,
and some googling leads me to think it's even possible to replace
the built-in serializers[1]).

See also: http://readthedocs.org/docs/django-testing-docs/en/latest/serialization.html

[0] https://docs.djangoproject.com/en/dev/ref/settings/#serialization-modules
[1] http://pypi.python.org/pypi/wadofstuff-django-serializers

Reply all
Reply to author
Forward
0 new messages