gpt4 book ai didi

python - Django Rest Framework ModelSerializer保存错误

转载 作者:行者123 更新时间:2023-11-30 22:54:35 24 4
gpt4 key购买 nike

我想从传递给序列化器的数据中添加一个额外的键值对,但是出现此错误:

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

序列化器.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()

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

url.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),
]

模型.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)

获取分数方法:

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() 方法时,不会发生此错误,并且实际上会保存该错误。然而,这将导致分数为空

我想在分数上添加一个值,该值来自数据的考试

最佳答案

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

在返回数据之前调用方法上的 super 将允许再次清理数据以及操作的分数数据键值。

关于python - Django Rest Framework ModelSerializer保存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37715373/

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