Getting one-to-many relationship data both ways in Django REST Framework

Viewed 1116

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?

1 Answers
class Building(models.Model):
    address = models.CharField(max_length = 200)
    zipcode = models.IntegerField()
    city = models.CharField(max_length = 100)
    def __str__(self):
        return self.address+self.city

class Tenant(models.Model):
    fname = models.CharField(max_length = 200)
    lname = models.CharField(max_length = 200)
    building = models.ForeignKey(Building, related_name = 'tenantsRN', on_delete = models.CASCADE)
    def __str__(self):
        return self.fname+self.lname+" tenant"


**#in serializers.py**
*#if you have not used related name u need to use _set*
class BuildingSerializer(serializers.HyperlinkedModelSerializer):
    tenantsRN=serializers.StringRelatedField(many=True)# gets self.fname+self.lname+" tenant"
    tenantsRN = serializers.SlugRelatedField(
                many=True,
                read_only=True,
                slug_field='fname')
    class Meta:
        model=Building
        fields = ('id', 'address', 'zipcode', 'city','tenantsRN')
        #you can use string related field or slug related field based on requirement
        #or you can use HyperlinkedIdentityField for customize

**in views.py**
class allview(ListAPIView):
    serializer_class=BuildingSerializer
    def get_queryset(self):
        return Building.objects.all()```
Related