Django json serialization problem
Posted
by
codingJoe
on Stack Overflow
See other posts from Stack Overflow
or by codingJoe
Published on 2010-12-25T07:50:05Z
Indexed on
2010/12/25
7:53 UTC
Read the original article
Hit count: 275
I am having difficulty serializing a django object. The problem is that there are foreign keys. I want the serialization to have data from the referenced object, not just the index.
For example, I would like the sponsor data field to say "sponsor.last_name, sponsor.first_name" rather than "13".
How can I fix my serialization?
json data: {"totalCount":"2","activities":[{"pk": 1, "model": "app.activity", "fields": {"activity_date": "2010-12-20", "description": "my activity", "sponsor": 13, "location": 1, ....
model code:
class Activity(models.Model):
activity_date = models.DateField()
description = models.CharField(max_length=200)
sponsor = models.ForeignKey(Sponsor)
location = models.ForeignKey(Location)
class Sponsor(models.Model):
last_name = models.CharField(max_length=20)
first_name= models.CharField(max_length=20)
specialty = models.CharField(max_length=100)
class Location(models.Model):
location_num = models.IntegerField(primary_key=True)
location_name = models.CharField(max_length=100)
def activityJSON(request):
activities = Activity.objects.all()
total = activities.count()
activities_json = serializers.serialize("json", activities)
data = "{\"totalCount\":\"%s\",\"activities\":%s}" % (total, activities_json)
return HttpResponse(data, mimetype="application/json")
© Stack Overflow or respective owner