简体   繁体   English

Django休息框架反向关系字段数据从validated_data中省略

[英]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 in data will be transmitted with a content type of multipart/form-data . 如果没有为content_type提供值,则data的值将以内容类型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. 在这种情况下,数据中的键值对将被编码为multipart消息,并用于创建POST数据有效负载。

You will need to explicitly specify the format of the data as json : 您需要以jsonformat明确指定数据的format

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用来自validated_data的kwargs的Django Rest Framework update() - Django Rest Framework update() with kwargs from validated_data Django Rest框架嵌套的序列化程序未在validated_data中返回关系值 - Django Rest framework nested serializer not returning relation values in validated_data Django-REST-Framework:ForeignKey实例未传递到validated_data - Django-REST-Framework: ForeignKey instance is not passed to validated_data Django rest框架:嵌套对象未传递给validated_data - Django rest framework: Nested object not passing to validated_data Django Rest Framework PUT视图说validated_data未填充 - Django Rest Framework PUT view saying validated_data is unfilled Django Rest框架可验证的嵌套序列化器数据从validated_data中丢失 - Django rest framework writeable nested serializer data missing from validated_data Django Rest 框架:在 def create() 方法之外访问验证数据 - Django Rest Framework: Accessing validated_data outside of def create() method Django Rest Framework Serializer 在 is_valid() 调用后弹出了validated_data,导致创建时出现KeyError - Django Rest Framework Serializer popped off the validated_data after is_valid() call, causing KeyError in create 将可编辑字段作为 Django-Rest-Framework 串行器的验证数据方法传递 - Passing Editable Fields as validated_data method of Django-Rest-Framework Serializer 使用 Django REST 发出 POST 请求时,validated_data 为空 - validated_data is empty when making POST request with Django REST
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM