drf django rest framework 尝试获取序列化程序“软件序列化程序”上字段“image_id”的值时出现 AttributeError(状态码 406)

Posted

技术标签:

【中文标题】drf django rest framework 尝试获取序列化程序“软件序列化程序”上字段“image_id”的值时出现 AttributeError(状态码 406)【英文标题】:erf django restframework Got AttributeError when attempting to get a value for field `image_id` on serializer `SoftwareSerializer' (status code 406) 【发布时间】:2022-01-22 04:24:16 【问题描述】:

我在尝试打开端点时遇到此错误 (http://127.0.0.1:8000/api/metrics/) 我正在使用 django restramework (drf),软件和类别端点工作正常,但度量端点给出以下错误:

错误


    "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

模型

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

观看次数

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()

序列化器

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

我搜索了很多但找不到解决方案,有人知道解决方案是什么吗? 提前致谢

【问题讨论】:

【参考方案1】:

您为 categorymetric 使用了错误的序列化程序。

代替

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

应该是

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

【讨论】:

以上是关于drf django rest framework 尝试获取序列化程序“软件序列化程序”上字段“image_id”的值时出现 AttributeError(状态码 406)的主要内容,如果未能解决你的问题,请参考以下文章

django-rest-framework(drf入门)

DRF(Django REST Framework)框架

是否过滤 Django Rest Framework (DRF) 中的代码示例优化问题

Django 学习之Django Rest Framework(DRF)

如何使 DRF ( Django-REST-Framework) 令牌保持不变,使其在每次页面刷新后不会丢失?

Django-rest-framework --- 总结