简体   繁体   中英

Is there a way to allow blank data for Django restframework

I have a products model that I want to have optional fields that are not required by the user whenever i try to input empty data it throws an error 400 back to the user meaning the serialized data is not valid

views.py

def products(request):
    if request.method == 'GET':
        products = Product.objects.filter(user=request.user)
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        serializer.initial_data['user'] = request.user.pk
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer.py

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

models.py

class Product(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(blank=True)
    price = models.FloatField()
    quantity = models.IntegerField(blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING)
    discount = models.FloatField(default=0)

The way DRF understands what field is required is by looking at your model field's option called null ( docs ).

If null=True , DRF will handle this field as not required

If you do not want to set this option in your model's class, you can make it work in serializer class via required option , eg

class ProductSerializer(serializers.ModelSerializer):
    name = serializer.CharField(required=False)

    class Meta:
        model = Product
        fields = '__all__'

You have to specifying fields explicitly and add required=false like this:

class ProductSerializer(serializers.ModelSerializer):
    # We make the description field empty
    description = serializers.CharField(max_length=200, required=False)
    class Meta:
        model = Product
        fields = ['name', 'description', 'user' , 'shop' ...] # Each field you want in the response.
        # Or you can use extra_kwargs since DRF 3.12.x
        extra_kwargs = {"description": {"required": False, "allow_null": True}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM