我无法使Django rest框架创建具有依赖关系的对象。简而言之,这是简化的配置,适用于其他部分更新,删除和创建Employee。但是在使用ForeignKey创建Case到Employee时失败了。
models.py
class Employee(models.Model):
firstName = models.CharField(max_length=50)
lastName = models.CharField(max_length=50)
class Case(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Employee, related_name='cases_created')
serializers.py
class SCase (serializers.HyperlinkedModelSerializer):
author = SEmployeeList(required = True)
class Meta:
model = models.Case
fields = ('url', 'title', 'author', 'id')
class SEmployee(serializers.HyperlinkedModelSerializer):
cases_created = SCaseList(many=True, required=False)
class Meta:
model = models.Employee
fields = ('url', 'firstName', 'lastName','cases_created', 'id')
views.py
class EmployeeViewSet(viewsets.ModelViewSet):
queryset = models.Employee.objects.all()
serializer_class = serializers.SEmployee
class CaseViewSet(viewsets.ModelViewSet):
queryset = models.Case.objects.all()
serializer_class = serializers.SCase
问题是当我创建对象案例时,必须引用作者。
POST
{"author":{"url":"http://localhost:8000/restbase/employee/23/",
"firstName":"Mark",
"lastName":"Hilton",
"cases_created":[],
"id":23},
"title":"New Case"
}
POST
{"author":"http://127.0.0.1:8000/restbase/employee/23/","title":"New Case"}
RESPONSE
{"author": [{"non_field_errors": ["Invalid data"]}]}
POST
{"author":{"url":"http://127.0.0.1:8000/restbase/employee/23/"},"title":"New Case"}
RESPONSE
{"author": [{"lastName": ["This field is required."], "firstName": ["This field is required."]}]}
答案 0 :(得分:0)
调查结束后,有一个有效的解决方案。作者无法序列化。
class SCase (serializers.HyperlinkedModelSerializer):
# removed line: author = SEmployeeList(required = True)
class Meta:
model = models.Case
fields = ('url', 'title', 'author', 'id')
我仍然不知道如何使用详细信息并创建依赖元素