gpt4 book ai didi

python - Django rest framework 反向关系字段数据从 validated_data 中省略

转载 作者:行者123 更新时间:2023-11-28 17:29:14 27 4
gpt4 key购买 nike

模型:

class Questionnaire(models.Model):
...

class Question(models.Model):
...
questionnaire = models.ForeignKey('Questionnaire', related_name='questions', blank=True, null=True)
...

序列化器:

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 使用 {'name': 'a', 'description': 'b', 'questions': [{'category': 'a', 'min_answers': 1}]}:

{u'name': u'a', u'questions': [], u'description': u'b'}

简单测试:

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 响应:

{u'description': u'b', u'id': 1, u'questions': [], u'name': u'a'}

我想编写嵌套字段并覆盖了 create 来这样做,但是验证似乎存在问题,因为嵌套模型的数据在 validated_data 中被删除。我尝试在创建函数的顶部打印 validated_data 变量,但由于我不理解的原因,questions 字段是一个空列表。 api-guide 文档中的关系部分显示了几乎完全相同的示例。我错过了什么?

编辑1:

序列化器直接在 shell 中测试时按预期工作,但由于某种原因它在测试用例中失败

编辑 2:查看:

class QuestionnaireViewSet(viewsets.ModelViewSet):
authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
permission_classes = [permissions.IsAuthenticated, ]
queryset = Questionnaire.objects.all()
serializer_class = QuestionnaireCreateUpdateSerializer

网址:

router = routers.DefaultRouter()
router.register(r'qnr', QuestionnaireViewSet)

urlpatterns = [
...
url(r'^api/', include(router.urls)),
]

最佳答案

由于您遵循了 api 指南中提供的示例并且它在 shell 中工作,我认为数据未正确发送。

Django Rest 框架使用 APIClient用于基于 Django 的 Test Client 的测试

如果您不提供内容类型,则默认值为multipart/form-data

If you don’t provide a value for content_type, the values in data will be transmitted with a content type of multipart/form-data. In this case, the key-value pairs in data will be encoded as a multipart message and used to create the POST data payload.

您需要将数据的格式明确指定为json:

response = self.client.post('/api/qnr/', data=qnr2, format='json')

关于python - Django rest framework 反向关系字段数据从 validated_data 中省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788667/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com