进行POST请求DRF时,此字段为必填错误

时间:2019-06-14 09:35:23

标签: python django django-rest-framework

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

POST请求的照片:

enter image description here

在我的代码下方提供。

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

错误:

enter image description here

所以我认为这可能是因为我添加了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之类的东西,但是我不确定。

希望你会看到,我在这里想念

1 个答案:

答案 0 :(得分:3)

覆盖 to_representation() 类的 DepartmentSerializer 方法,并通过继承创建 DescriptionOrganizationSerializer serializers.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: Simple foreign key assignment with nested serializers?--SO post