django.db.utils.IntegrityError:在POST请求中

时间:2019-08-24 07:12:23

标签: django django-rest-framework

我正在创建一个发布函数以将数据保存在模型中,这是代码:

Views.py

class take_quizapi(CreateAPIView):

    def post(self, request,pk, *args, **kwargs):
        supplier = request.user.supplier

        data = request.data.copy()
        data["supplier_id"] = supplier.user_id
        data["score"] = 0
        data["quiz"] = pk
        print("data is", data)
        serializer = takenquizSerializer(data=data)

        if serializer.is_valid():
            serializer.save()
            print("Serializer data", serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

当我从邮递员那里调用API时,它说:

  

django.db.utils.IntegrityError:“ supplier_id”列中的空值违反了非空约束

但是我显然提供了data["supplier_id"] = supplier.user_id。 我在这里做错什么了?

Serializers.py

class takenquizSerializer(serializers.ModelSerializer):
    supplier = ReadOnlyField(source='supplier.supplier_fname')
    class Meta:
        model = TakenQuiz
        fields = "__all__"

Models.py

class TakenQuiz(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes')
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes')
    score = models.FloatField()
    date = models.DateTimeField(auto_now_add=True)
    least_bid = models.IntegerField(default=0)
    confirmed = models.CharField(max_length=100, default='Not Confirmed')

1 个答案:

答案 0 :(得分:0)

supplier是一个只读字段。因此,将其添加到数据字典中没有意义,因为它将永远不会使用。

无论如何,您都不应该修改发布数据-这是不可变的。代替pass it in when saving

serializer = takenquizSerializer(data=request.data)

if serializer.is_valid():
    serializer.save(supplier_id=supplier.user_id, score=0, quiz=pk)