[Answered ]-Django: One-to-Many and Many-to-One Serializers and Queries

1👍

Use related_name keyword in your models, you can learn more about it — here is how it works–

  1. Define you models and add related_name to the foreign keys as –

    class City(models.Model):
         ##fields
    
     class Building(models.Model):
         cityId = models.ForeignKey(City, on_delete=models.CASCADE,related_name='abc')
    
     class Device(models.Model):
         buildingId = models.ForeignKey(Building, on_delete=models.CASCADE, related_name='xyz')
    
  2. Then define your serializers in reverse order and add the related_name of models in your serializers field–

     class DeviceSerializer(serializers.ModelSerializer):
         class Meta:
             model = Device
             fields = ['id', 'buildingId', ...]
    
     class BuildingSerializer(serializers.ModelSerializer):
         xyz = DeviceSerializer(many=True, read_only=True)
         class Meta:
             model = Building
             fields = ['id', 'cityId', xyz ...]
    
     class CitySerializer(serializers.ModelSerializer):
         abc = BuildingSerializer(many=True, read_only=True)
         class Meta:
             model = City
             fields = ['id', 'abc' ...]
    

Now when you will try to get the city, you will get all the building rel;ated to that city and also all the Devices related to each building.

There is one another method called as serializermethodfield, this is of great use in many areas, you can use any one depending upon your choice.

Hope this helps..

Leave a comment