I'm using Django REST Framework to create the following endpoints:
/tenants/ ➞ lists all tenants and includes in the json response the attributes of the Building model they live in.
/buildings/ ➞ lists all buildings and includes in the json response the attributes of the Tenants that live in them.
My models are:
class Building(models.Model):
address = models.CharField(max_length = 200)
zipcode = models.IntegerField()
city = models.CharField(max_length = 100)
class Tenant(models.Model):
fname = models.CharField(max_length = 200)
lname = models.CharField(max_length = 200)
building = models.ForeignKey(Building, related_name = 'tenants', on_delete = models.CASCADE)
My serializers look like so:
class BuildingSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
fields = ['id', 'address', 'zipcode', 'city']
class TenantSerializer(serializers.HyperlinkedModelSerializer):
building = BuildingSerializer()
class Meta:
model = Tenant
fields = ['id', 'fname', 'lname', 'building']
The /tenants/ endpoint works just fine, but I have no idea on how to include the tenants' data in the /buildings/ response.
Could anyone give me a clue on this?