当我试图通过浏览器发布时,请求无法保存字段organization
。你知道吗
发帖照片:
请提供以下我的代码。你知道吗
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
之类的内容,但我不确定。你知道吗
希望你能看到,我在这里错过了什么
重写
DepartmentSerializer
类的to_representation()
方法,并通过仅继承类来创建DescriptionOrganizationSerializer
类。你知道吗参考:DRF: Simple foreign key assignment with nested serializers? SO post
相关问题 更多 >
编程相关推荐