2016-03-04 19 views
3

機型:Django的其餘框架反向從validated_data省略關係字段數據

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 
      ... 

使用{'name': 'a', 'description': 'b', 'questions': [{'category': 'a', 'min_answers': 1}]} validated_data:

{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文檔中的關係部分顯示了幾乎完全相同的示例。我錯過了什麼?

EDIT1:

串行器工作時,在外殼直接測試符合預期,但由於某些原因,它在測試用例失敗

編輯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)), 
    ] 
+0

您還可以添加'QuestionSerializer'? – AKS

+0

@AKS添加了串行器 –

+1

在這裏一切都看起來不錯。您是否試圖在控制檯中執行此操作,如api-guide [示例]中所示(http://www.django-rest-framework.org/api-guide/relations/#writable-nested-srializers)? – AKS

回答

2

由於您遵循了示例prov在api-guide中找到並且它在shell中工作我認爲數據沒有正確發送。

Django的REST框架用來測試APIClient它是基於Django的Test Client

如果不提供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 . In this case, the key-value pairs in data will be encoded as a multipart message and used to create the POST data payload.

您將需要顯式地指定的format數據爲json

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