How to serialize objects that contain a foreign key object

4,362 views
Skip to first unread message

Ariel

unread,
Feb 9, 2010, 5:04:39 PM2/9/10
to django...@googlegroups.com
I need to serialize a an object that has a foreign key object for example:
I have this model:

class Town(models.Model):
    name = models.CharField(max_length=50)
    extension = models.IntegerPositiveField()

class Restaurant(models.Model):
    hot_dogs = models.BooleanField()
    town = models.ForeignKey(Town)


from django.core import serializers

json_serializer  = serializers.get_serializer("json")
data = json_serializer.serialize(Restaurant.objects.alI(), ensure_ascii=False)

But problem is that when the list of restaurant objects are serialized only the primary key of the town object is serialized but not the name and the extension, this is what I get:
[ {pk : '1', hot_dogs: 'True' , town: '1'}, {pk : '2', hot_dogs: 'False' , town: '1'}, {pk : '3', hot_dogs: 'True' , town: '2'} ]

And I would want to get the name and the extension of the town foreign key object too.
I hope you can help me

Thanks in advance.
Regards
Ariel

diofeher

unread,
Feb 10, 2010, 8:39:30 AM2/10/10
to Django users
Django 1.2 comes with a parameter [1] at serializers that do this for
you.

http://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys

Ariel

unread,
Feb 10, 2010, 12:42:13 PM2/10/10
to django...@googlegroups.com
I am using version 1.1, Could I do the same with 1.1 version ???


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


Ramiro Morales

unread,
Feb 10, 2010, 4:26:17 PM2/10/10
to django...@googlegroups.com
On Wed, Feb 10, 2010 at 2:42 PM, Ariel <isaa...@gmail.com> wrote:
> I am using version 1.1, Could I do the same with 1.1 version ???
>
> On Wed, Feb 10, 2010 at 7:39 AM, diofeher <diof...@gmail.com> wrote:
>>
>> Django 1.2 comes with a parameter [1] at serializers that do this for
>> you.
>>
>> http://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys
>>

Unfortunately no. We didn't mark appropiately that documentation section
as a new 1.2 feature. I've opened ticket [1]#12840 for that.

For your original problem, you might want to try the external
project [2]'Django full serializers' by Matthew Flanagan.

HTH

--
Ramiro Morales | http://rmorales.net

1. http://code.djangoproject.com/ticket/12840
2. http://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers

Reply all
Reply to author
Forward
0 new messages