IntegrityError - 列不能为空DJANGO

时间:2017-03-17 14:36:29

标签: python django django-rest-framework serializer

一切在视图和模板中都很好用。当我制作序列化器然后APIVIew发生了错误的事情。 GET方法没问题,但POST没有。当我尝试添加食物时,我得到像这样的IntegrityError :(但是在管理面板和GUI中你可以正常添加食物,所以它的问题不是模型,问题必须是序列化器)

  

/ food_list_serializer /

中的IntegrityError      

列'kcal'不能为空

MODEL看起来像这样:

class Food(models.Model):
    name = models.CharField(max_length=124)
    kcal = models.FloatField()
    proteins = models.FloatField()
    carbs = models.FloatField()
    fats = models.FloatField()
    grams = models.FloatField(default=100, validators=[MinValueValidator(1)])

串行:

class FoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = Food
        fields = '__all__'

视图:

class FoodListSerializer(APIView):
    def get(self, request, format=None):
        food = Food.objects.all()
        serializer = FoodSerializer(food, many=True, context={'request': request})
        return Response(serializer.data)

    def post(self, request):
        food_create = Food.objects.create()
        serializer = FoodSerializer(food_create, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

POST request in DJANGO rest framework looks like this

1 个答案:

答案 0 :(得分:0)

问题出在这一行:

food_create = Food.objects.create()

在实际解析Food数据之前,您告诉Django在零参数的数据库中创建并保存POST对象。在Food模型中,您需要很多字段(其中一个是kcal字段)。删除此行,因为FoodSerializer将被填充"使用request.dataPOST)值。