On Mon, Aug 15, 2011 at 5:58 PM, Christo Buschek <cr...@30loops.net> wrote:
> Hi list,
>
> I'm busy writing a custom json serializer for django. It works very
> good, only now I want to serialize ForeignKey and M2M relations inside
> the same serialization call and build nested json objects with all model
> instances that the current model instance relates to.
>
> {'field_a': 'value',
>  'field_b': 'value',
>  'field_c': {             <-- Nest Foreign Keys
>    'field_d': 'value',
>    'field_e': 'value',
>  },
>  'field_f': [             <-- Nest M2M
>    {'field_g': 'value'},
>    {'field_h': 'value'}
>  ]
> }
>
> I found https://code.djangoproject.com/ticket/4656 that discusses this
> problem, but, from what I understood, is not offering a clean solution yet.
>
> So I actually have 2 questions:
>
> 1) Is there an "common way" how people do that? I'm sure other people
> were doing thesame thing already. I found
> http://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers that
> seems to do exactly this, but if possible I prefer not to use another
> 3rd party dependency.

There isn't any way that I'd call sufficiently common to say that
everyone does it.

If you search the django-developers archives around July, there was a
proposal to improve Django's serializers [1]. I worked with Tom during
DjangoCon Europe to develop this API, and I think it's getting close
to being suitable for trunk. This effort covers a multitude of
requirements, including nested m2m relationships.

[1] 
http://groups.google.com/group/django-developers/browse_thread/thread/1f610a641b119456

> 2) I found 'a way' where I iterate through each field of the model and
> test the field in the following way:
>
>  if type(a._meta.get_field('field_c')) == models.ForeignKey:
>     # follow relation and serialize it
>
> Now is it a smart idea to access the model option with _meta, or can I
> expect this not to work anymore with the next django release?

The _meta block has a weird sort of "unofficially stable" status.
Technically, it isn't covered by our backwards compatibility
guarantee. However, there is so much code out there using it that if
we were to make any changes, it would cause a major upheaval in the
Django world, so in practice, it's not likely to change very much.
Formalizing the _meta API is something that is on the todo list.

As a rough rule of thumb, the more "obvious" API points, the more
likely it is to be baked in as official when we get around to
formalizing. Calls like "get_field" are almost guaranteed to be stable
*

* Not a guarantee :-)

Yours,
Russ Magee %-)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to