[Solved]-How do I make Django-Piston to include related child objects in the serialized output?


Ok so I got it working finally after debugging thru emitters.py and noting how it uses the ‘fields’ property of the handler to iterate the Model fields.

These are my models:

class Building(models.Model):
    address         = models.CharField(max_length=255)

    def __unicode__(self):
        return self.address 

class BuildingArea(models.Model):
    display_name  = models.CharField(max_length=30)
    building      = models.ForeignKey(Building, related_name='areas') 

    def __unicode__(self):
        return self.display_name 

This is what my BuildingHandler looks like now:

class BuildingHandler(BaseHandler):

    allowed_methods = ('GET',)    
    fields = ('address', ('areas', ('display_name',),),)    
    model = Building

    def read(self, name=None):
        return self.model.objects.all()

The important thing to note here is that emmitters.py will activate certain codepaths only if the current field definition is a set or a list. I had forgotten to add a trailing ‘,’ to the sets used to define the fields and this caused Piston to cause Python to return a set made of the characters contained in the string, ‘display_name’, rather than a set containing the string ‘display_name’. I hope that made sense, Google ‘Python single set trailing comma’ for more info.

Hopefully this helps someone else! 😀


On BuildingHandler, do:

fields = ('address', 'areas')

That should do it.

Leave a comment