2016-06-09 102 views
1

我想從我傳遞給串行數據添加額外的鍵值對但是出現此錯誤:Django的REST框架ModelSerializer保存錯誤

ValueError: Cannot assign "1": "ExamLog.student" must be a "Students" instance. 

serializers.py

class ExamSubmitSerializer(serializers.ModelSerializer): 
    def to_internal_value(self, data): 
     x = get_score(data['exam']) # This will result to 1, I have no errors with this one 
     data['score'] = x 
     return data 

    class Meta: 
     model = ExamLog 
     fields = ('student', 'score', 'exam_started') 

    # Will use this one for auto-email and auto-pdf creation 
    # def create(self, validated_data): 
    # # print "-----" 
    # # y = validated_data.pop('exam', None) 
    # # print y 
    # print validated_data 
     # x = self.Meta.model(**validated_data) 
     # x.save() 

views.py

@api_view(['POST']) 
def submitExam(request): 
    if request.method == 'POST': 
     data = request.data 
     student = data.get('student', None) 
     exam = data.get('exam', None) 
     serializer = ExamSubmitSerializer(data=data) 
     if serializer.is_valid(): 
      serializer.save() 
      return Response(standardResponse(data=serializer.data), status=status.HTTP_201_CREATED) 
     else: 
      return Response(standardResponse(errors=serializer.errors), status=status.HTTP_400_BAD_REQUEST) 

urls.py

urlpatterns = [ 
    # url(r'^view/', views.viewExams), 
    url(r'^view/', views.getQuestion), 
    url(r'^add/', views.addUpdateQuestion), 
    url(r'^submit/', views.submitExam), 
    url(r'^', views.filterQuestions), 
] 

models.py

class Choices(models.Model): 
    question = models.ForeignKey(Questions) 
    choice = models.TextField() 
    correct = models.NullBooleanField() 

    def __unicode__(self): 
     return self.choice 

class ExamLog(models.Model): 
    student = models.ForeignKey(Students) 
    # answers = models.JSONField? # To be used for data science statistical purposes 
    score = models.PositiveIntegerField(null=True, blank=True, default=None) 
    exam_started = models.DateTimeField(null=True, blank=True, default=None) 
    exam_finished = models.DateTimeField(auto_now_add=True) 

get_score方法:

def get_score(answers): 
    x = Choices.objects.filter(id__in=answers).filter(correct=1) 
    return x.count() 

樣品請求API:

{"student":1, "exam":[ 1597, 1620, 1906, 1648, 1656, 1718, 1611, 1551, 1812, 1745, 1489, 1815, 1527, 1485, 1512, 1831, 1545, 1713, 1808, 1530 ]} 

我明白什麼意思的錯誤。應該傳遞模型的實例而不是其ID,但是,如果不包含to_internal_value()方法,則不會發生此錯誤並實際保存。然而,這將導致對比分爲空

我想補充的分數值將來自數據

回答

2
def to_internal_value(self, data): 
    x = get_score(data['exam']) # This will result to 1, I have no errors with this one 
    data['score'] = x 

    data = super(ExamSubmitSerializer, self).to_internal_value(data) 

    return data 

呼籲方法超之前的考試關鍵返回數據將允許再次清理數據以及操縱的分數數據鍵值。

相關問題