首页 > 解决方案 > 必填 POST 请求 DRF 时出错

问题描述

当我尝试通过浏览器发布时,请求无法保存字段organization

POST 请求的照片:

在此处输入图像描述

在我的代码下方提供。

serializers.py

class DescriptionOrganizationSerializer(serializers.PrimaryKeyRelatedField, serializers.ModelSerializer):

    class Meta:
        model = Organization
        fields = ("id", "org_name")


class DepartmentSerializer(serializers.ModelSerializer):
    emp_count_for_dep = serializers.SerializerMethodField()
    organization = DescriptionOrganizationSerializer(queryset=Organization.objects.all())

    class Meta:
        model = Department
        fields = '__all__'

models.py

class Organization(models.Model):
    org_name = models.CharField(max_length=100)

    def __str__(self):
        return self.org_name


class Department(models.Model):
    dep_name = models.CharField(max_length=100)
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE,
                                     related_name='departments')

    def __str__(self):
        return self.dep_name

views.py

class DepartmentView(viewsets.ModelViewSet):

    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer

错误:

在此处输入图像描述

所以我认为这可能是因为我添加了queryset=Organization.objects.all()-PrimaryKeyRelatedField没有它,我无法选择organization字段并出现另一个错误(我解决了它,但在这里提供它,因为这可以帮助你更多地理解我的代码):

AssertionError at /api/v1/department/

The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `api.serializers.DepartmentSerializer`, or set `read_only=True` on nested serializer fields.

另一个想法是ForeignKey组织模型需要更改为类似的东西OneToManyField,但我不确定。

希望你会看到,我在这里错过了什么

标签: pythondjangodjango-rest-framework

解决方案


重写类的方法to_representation()继承类来DepartmentSerializer创建类。DescriptionOrganizationSerializerserializers.ModelSerializer

class DescriptionOrganizationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organization
        fields = ("id", "org_name")


class DepartmentSerializer(serializers.ModelSerializer):
    emp_count_for_dep = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = '__all__'

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['organization'] = DescriptionOrganizationSerializer(instance.organization).data
        return rep

参考DRF:使用嵌套序列化程序的简单外键分配?——所以发帖


推荐阅读