python - 必填 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
,但我不确定。
希望你会看到,我在这里错过了什么
解决方案
重写类的方法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
推荐阅读
- php - 如何将请求对象从表单传递到 PHP
- javascript - 如何使用 firebaseServer 检索 Firebase 数据?
- operating-system - 我们可以通过覆盖段寄存器来绕过用户模式/内核模式限制吗?
- c - 如何在井字游戏中预测玩家 X 或 O 的获胜位置并告诉用户该位置?
- stan - 从 Stan 输出表中提取平均参数估计
- sql - 选择 Oracle 中最年长和最年轻的员工
- c# - 如何在 C# 中将特定列从 DataGridView 导出到 Excel 或 CSV?
- javascript - 在顶点图表中使用变量作为数据
- laravel - 没有认证的新 laravel 项目
- git - 从 git 安装并执行 rpy2