How to best nest info of through model in Serializer

40 views
Skip to first unread message

Remco Wendt

unread,
May 24, 2013, 11:44:12 AM5/24/13
to django-res...@googlegroups.com
# Models.py

class Facility(models.Model):
    name = models.CharField(max_length=255, unique=True)
    icon = models.CharField(max_length=255, blank=True)

class ProvidesLocationFacility(models.Model):
    facility = models.ForeignKey('Facility')
    location = models.ForeignKey('Location', verbose_name=_('location'))

    is_free = models.BooleanField()

class Location(models.Model):
    name = models.CharField(blank=False, max_length=255, db_index=True)
    facilities = models.ManyToManyField(
        'Facility', through='ProvidesLocationFacility')

    def provides_facilities(self):
        return ProvidesLocationFacility.objects.filter(location=self.pk)
        

# Serializers.py

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ('name', 'provides_facilities')
        
        
So I have a Location that provides facilities. These facilities are generic: wifi, printer, etc. I use a through model so I can configure per location which facilities they have and whether the facility is free or not. 

I want the LocationSerializer to nest the data of the ProvidesLocationFacility (which again nests the Facility model data). What is the best way to do this? I already have created a provides_facilities method on the Location model.

Cheers,
Remco
Reply all
Reply to author
Forward
0 new messages