Search code examples
djangopython-3.xdjango-rest-frameworkdjango-serializer

TypeError: 'int' object is not iterable serializer Django Serializer for one-to-many


I am facing a strange situation, Following is my code for models.

class Sector(models.Model):
    sector_name = models.CharField(max_length=255, null=False)
    sector_desc = models.CharField(max_length=1024, null=False)

    def __set__(self):
        return "{} - {}".format(self.sector_name, self.sector_desc)


class TrailCompany(models.Model):
    sector = models.ForeignKey(Sector, on_delete=models.CASCADE, related_name="sector_id")
    comp_name = models.CharField(max_length=255, null=False)
    comp_desc = models.CharField(max_length=1024, null=False)

    def __set__(self):
        return "{} - {}".format(self.sector, self.comp_name, self.comp_desc)


class Trail(models.Model):
    company = models.ForeignKey(TrailCompany, on_delete=models.CASCADE, related_name="company_id")
    trail_id = models.CharField(max_length=255, null=False)
    tri = models.CharField(max_length=255, null=False)
    exp_pdufa = models.CharField(max_length=255, null=False)

    def __set__(self):
        return "{} - {}".format(self.company, self.exp_pdufa, self.trail_id, self.tri, self.exp_pdufa)

Following is my code for the serializer,

class SectorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Sector
        fields = '__all__'


class TrailCompanySerializer(serializers.ModelSerializer):
    sectors = SectorSerializer(source="sector_id", many=True)

    class Meta:
        model = TrailCompany
        fields = '__all__'


class TrailSerializer(serializers.ModelSerializer):
    companies = TrailCompanySerializer(source="company_id", many=True)

    class Meta:
        model = Trail
        fields = '__all__'

When I try to serilize object I am getting the stated error,

trail_query = Trail.objects.all()
        trails = TrailSerializer(trail_query, many=True)
        return Response({"success": True, 'trails': trails.data})

Please help me to figure out and resolve the problem. Thanks.


Solution

  • Looks like your error is in the following line:

    companies = TrailCompanySerializer(source="company_id", many=True)
    

    Trail<>TrailCompany is a one to one relationship from the perspective of Trail. E.g. the Trail only knows of one TrailCompany it is related to. Therefore you do not need the many=True attribute.

    I also think the source should be company rather than company_id. company_id is a primary key, whereas company is the related object