0

When I try to POST through the browser, request can't save field organization.

Photo of POST request:

enter image description here

Provide below my code.

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

Error:

enter image description here

So I think it's maybe because I added queryset=Organization.objects.all() and PrimaryKeyRelatedField - without that, I can't select organization field and got another error (I solve it, but provide it here because this could help you understand my code more):

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.

Another thought is ForeignKey in Organization model need to be changed to something like OneToManyField, but I'm not sure.

Hope you will see, what I am missed here

Dmitriy Kisil
  • 2,858
  • 2
  • 16
  • 35

1 Answers1

1

Override the to_representation() method of DepartmentSerializer class, and create DescriptionOrganizationSerializer class by inheriting only the serializers.ModelSerializer class.

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

Reference: DRF: Simple foreign key assignment with nested serializers?--SO post

JPG
  • 82,442
  • 19
  • 127
  • 206
  • many thanks! I replicate this approach on another serializers, where have two fields instead of one here - and this still works! After checking reference, I found the typo in `Complete representaion of Serializer` (missed letter `t`) but SO can't allow me to edit one letter – Dmitriy Kisil Jun 14 '19 at 10:03