[英]Django rest framework reverse relation field data omitted from validated_data
models: 楷模:
class Questionnaire(models.Model):
...
class Question(models.Model):
...
questionnaire = models.ForeignKey('Questionnaire', related_name='questions', blank=True, null=True)
...
serializers: 串行:
class QuestionSerializer(serializers.ModelSerializer):
choices = MultipleChoiceSerializer(many=True)
children = RecursiveField(many=True)
class Meta:
model = Question
fields = [
'id',
'text',
'order',
'choices',
#'parent',
'children',
'type',
'category',
'requiredif',
'max_answers',
'min_answers',
]
class QuestionnaireCreateUpdateSerializer(serializers.ModelSerializer):
questions = QuestionSerializer(many=True)
class Meta:
model = Questionnaire
fields = [
'id',
'questions',
'name',
'description',
]
def create(self, validated_data):
print validated_data
...
validated_data using {'name': 'a', 'description': 'b', 'questions': [{'category': 'a', 'min_answers': 1}]}
: validated_data使用
{'name': 'a', 'description': 'b', 'questions': [{'category': 'a', 'min_answers': 1}]}
:
{u'name': u'a', u'questions': [], u'description': u'b'}
simple test: 简单测试:
def test_submit_qnr(self):
self.client.force_login(self.user.user)
qnr2 = {'name': 'a', 'description': 'b', 'questions': [{'category': 'a', 'min_answers': 1}]}
response = self.client.post('/api/qnr/', data=qnr2)
print response.json()
response.json()['questions'].should_not.equal([]) # fails!
JSON response: JSON响应:
{u'description': u'b', u'id': 1, u'questions': [], u'name': u'a'}
I would like to write nested fields and have overridden create
to do so, but there seems to be an issue with validation, in that the data for the nested models is deleted in the validated_data. 我想编写嵌套字段并覆盖
create
来执行此操作,但似乎验证存在问题,因为嵌套模型的数据将在validated_data中删除。 I tried printing the validated_data
variable at the top of the create function and for reasons I don't understand the questions
field is an empty list. 我尝试在create函数的顶部打印
validated_data
变量,并且由于我不理解questions
字段是一个空列表。 The relations section in the api-guide documentation shows almost this exact same example. api-guide文档中的关系部分显示了几乎完全相同的示例。 What am I missing?
我错过了什么?
EDIT1: EDIT1:
The serializer works as expected when tested directly in the shell, but for some reason it fails in the test case 串行器在shell中直接测试时按预期工作,但由于某种原因,它在测试用例中失败了
EDIT 2: View: 编辑2:查看:
class QuestionnaireViewSet(viewsets.ModelViewSet):
authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
permission_classes = [permissions.IsAuthenticated, ]
queryset = Questionnaire.objects.all()
serializer_class = QuestionnaireCreateUpdateSerializer
URLs: 网址:
router = routers.DefaultRouter()
router.register(r'qnr', QuestionnaireViewSet)
urlpatterns = [
...
url(r'^api/', include(router.urls)),
]
Since you followed the example provided in the api-guide and it works in shell I think that the data is not being sent properly. 由于您遵循api-guide中提供的示例并且它在shell中工作,我认为数据未正确发送。
Django Rest Framework uses APIClient
for testing which is based on Django's Test Client
Django Rest Framework使用
APIClient
进行测试,该测试基于Django的Test Client
If you don't provide a content type
the default value is multipart/form-data
如果您不提供
content type
则默认值为multipart/form-data
If you don't provide a value for
content_type
, the values indata
will be transmitted with a content type ofmultipart/form-data
.如果没有为
content_type
提供值,则data
的值将以内容类型multipart/form-data
。 In this case, the key-value pairs in data will be encoded as amultipart
message and used to create thePOST
data payload.在这种情况下,数据中的键值对将被编码为
multipart
消息,并用于创建POST
数据有效负载。
You will need to explicitly specify the format
of the data as json
: 您需要以
json
的format
明确指定数据的format
:
response = self.client.post('/api/qnr/', data=qnr2, format='json')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.