{"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]}

{"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]}

文件company.py(型号)

from django.db import models

COMPANY_TYPE = [('ИП', 'ИП'), ('АО', 'АО'), ('ТОО', 'ТОО')]


class Company(models.Model):
    name = models.CharField(blank=False, max_length=255)
    company_type = models.CharField(blank=False, max_length=10, choices=COMPANY_TYPE, default='ИП')
    logo = models.CharField(blank=False, max_length=255)
    owner = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='companies')
    average_review = models.FloatField(blank=True, default=0, editable=True)
    count_of_review = models.IntegerField(blank=True, default=0, editable=True)
    created_date = models.DateTimeField(blank=False, auto_now_add=True)
    last_change_date = models.DateTimeField(blank=False, auto_now=True)

    def __str__(self):
        return self.name

views.py

class CompanyDetailView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, company_id):
        data = get_object_or_404(Company, id=company_id)
        payload = CompanyDetailSerializer(data=data)
        payload.is_valid(raise_exception=True)
        return Response(payload.data)

serializers.py

class CompanyDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('id', 'name', 'company_type', 'logo', 'owner', 'average_review', 'count_of_review', 'created_date', 'last_change_date')

但是它returns数据

{"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]}

我找不到任何解决方案,我只是开始在 rest 框架中编码)

从您的代码中删除 payload.is_valid(raise_exception=True)

我们在 POSTUpdate 端点中使用它来确保请求正文包含我们需要接收的数据

查看这些链接了解更多信息Link1 , Link2