When I try to POST through the browser, request can't save field organization
.
Photo of POST request:
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:
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