Home > database >  erf django restframework Got AttributeError when attempting to get a value for field `image_id` on s
erf django restframework Got AttributeError when attempting to get a value for field `image_id` on s

Time:12-22

I am facing this error when trying to open the endpoint (http://127.0.0.1:8000/api/metrics/) I am using django restramework (drf), software and category enpoints are working fine, but the metric endpoint is giving the following error:

Error

{
    "message": "Got AttributeError when attempting to get a value for field `image_id` on serializer `SoftwareSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `Category` instance.\nOriginal exception text was: 'Category' object has no attribute 'image'.",
    "code": null,
    "status_code": 406
}

Models

class Category(models.Model):
    name = models.CharField(max_length=256, blank=True)
    created_datetime = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ ایجاد ")
    update_datetime  = models.DateTimeField(auto_now=True, verbose_name="تاریخ بروزرسانی ")

    def __str__(self):
        return self.name

class Metric(models.Model):
    title = models.CharField(max_length=254)
    categorymetric = models.ForeignKey("main.Category",on_delete=models.SET_NULL,null=True)

    def __str__(self):
        return self.title

class Software(models.Model):
    software_name   = models.CharField(max_length=150, default="software_name", null=False, verbose_name="اسم نرم افزار")
    created_datetime = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ ایجاد ")
    update_datetime  = models.DateTimeField(auto_now=True, verbose_name="تاریخ بروزرسانی ")
    image            = models.ForeignKey("main.Image", on_delete=models.SET_NULL, blank=True, null=True)
    created_by       = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True)
    
    class Meta:
         verbose_name = "software"
         verbose_name_plural = "softwares"

    def __str__(self) :
          return self.software_name

Views

class CategoryViewSet(ModelViewSet):
    serializer_class = CategorySerializer
    pagination_class = None
    queryset = Category.objects.all()

class SoftwareViewSet(ModelViewSet):
    serializer_class = SoftwareSerializer
    pagination_class = None
    queryset = Software.objects.all()
    permission_classes = ( IsAuthenticated, )
    
    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

class MetricViewSet(ModelViewSet):
    serializer_class = MetricSerializer
    pagination_class = None
    queryset = Metric.objects.all()

Serializers

class MetricSerializer(serializers.ModelSerializer):
    categorymetric = SoftwareSerializer(read_only=True)
    categorymetric_id = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), source='Categorymetric')
    class Meta:
        model = Metric
        fields = ['id', 'title', 'categorymetric','categorymetric_id']

class CategorySerializer(serializers.ModelSerializer):
    class Meta :
        model =Category
        fields = ['id','name','created_datetime','update_datetime']

class SoftwareSerializer(serializers.ModelSerializer):
    image = ImageSerializer(read_only=True)
    image_id = serializers.PrimaryKeyRelatedField(queryset=Image.objects.all(), source='image')
    
    class Meta:
        model = Software
        fields = ['id', 'software_name','created_datetime','update_datetime','image','image_id', 'created_by']
        depth = 1

I searched alot but could not find the solution, Anyone have any idea what's the solution? Thanks in advance

CodePudding user response:

You used the wrong serializer for the categorymetric.

Instead of

class MetricSerializer(serializers.ModelSerializer):
    categorymetric = SoftwareSerializer(read_only=True)

it should be

class MetricSerializer(serializers.ModelSerializer):
    categorymetric = CategorySerializer(read_only=True)
  • Related