0
class Room (models.Model):
    restaurant = models.ForeignKey(Restaurant,verbose_name='Restaurant', on_delete=models.CASCADE)
    room_name = models.CharField(max_length=50,verbose_name='Room Name')
    def __str__(self):
        return self.room_name

class Table (models.Model):
    room = models.ForeignKey(Room,on_delete=models.CASCADE)
    capacity = models.IntegerField()
    name = models.CharField(max_length=30,verbose_name='Table Name')

    def __str__(self):
        return self.room.room_name + ': ' + self.name

I'm using django to build an API and I want to return these models as a JSON. The problem is that when I return a Room object the Tables are not in the JSON. How can I serialise a Room and also get the tables serialised with it.

This is how I'm serialising the Room:

rooms = Room.objects.filter(restaurant=id)
return HttpResponse(serializers.serialize("json", rooms))

The problem is that the reverse relationship is not being included.

Rukia Kuchiki
  • 120
  • 1
  • 9
  • How did you serialize your models? – Shang Wang Apr 18 '16 at 16:32
  • I'll edit the question – Rukia Kuchiki Apr 18 '16 at 16:34
  • Possible duplicate of [Serializing Foreign Key objects in Django](http://stackoverflow.com/questions/3753359/serializing-foreign-key-objects-in-django) – ahmed Apr 18 '16 at 16:48
  • It's not, that question is for resolving the keys to their objects. This is for including nested objects when serialising. – Rukia Kuchiki Apr 18 '16 at 16:53
  • 1
    I believe the default django serializers doesn't do this (I would love to be corrected). You may have to write your own or use another one. I personally like the one from django-rest-framework. – hndr Apr 18 '16 at 17:14

0 Answers0