Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework "A valid integer is required."?

I want to default an empty string to a 0 or null during deserialization.

JSON

{
  'injuries': '6',
  'children': '2',
  'civilians': '',
}

However, I keep getting this error:

"A valid integer is required."

models.py

from django.db import models    

class Strike(models.Model):
    location = models.ForeignKey('Location', on_delete=models.CASCADE)
    civilians = models.PositiveIntegerField(blank=True, null=True)
    injuries = models.PositiveIntegerField(blank=True, null=True)
    children = models.PositiveIntegerField(blank=True, null=True)

serializers.py

from rest_framework import serializers
from .models import Strike


class StrikeSerializer(serializers.ModelSerializer):
    civilians = serializers.IntegerField(default=0, required=False)

    class Meta:
        model = Strike
        fields = '__all__'

    def create(self, validated_data):
        return Strike.objects.create(**validated_data)

main

serializer = StrikeSerializer(data=strike)

I tried manipulating data in create method, but the error gets raised before that. Where in the DRF structure can I override this, specifically convert '' to 0 or None?

like image 492
Saša Kalaba Avatar asked Apr 10 '18 12:04

Saša Kalaba


People also ask

How do I handle exceptions in Django REST framework?

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

What is Read_only true in Django?

read_only. Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

What is Serializers SerializerMethodField ()?

Serializer Method Field This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. SerializerMethodField gets its data by calling get_<field_name> .


1 Answers

You can use a CharField and then convert to int in the validation method.

class StrikeSerializer(serializers.ModelSerializer):
    civilians = serializers.CharField(
            required=False, allow_null=True, allow_blank=True)

    def validate_civilians(self, value):
        if not value:
            return 0
        try:
            return int(value)
        except ValueError:
            raise serializers.ValidationError('You must supply an integer')
like image 56
Daniel Roseman Avatar answered Oct 04 '22 03:10

Daniel Roseman