gpt4 book ai didi

python - 有没有办法允许 Django 休息框架的空白数据

转载 作者:行者123 更新时间:2023-12-05 02:36:56 31 4
gpt4 key购买 nike

我有一个产品模型,我希望有用户不需要的可选字段每当我尝试输入空数据时,它都会向用户抛出错误 400,这意味着序列化数据无效

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

序列化器.py

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

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

最佳答案

DRF 了解需要什么字段的方式是查看模型字段的名为 null (docs) 的选项。

如果null=True,DRF 将按不需要处理此字段

如果您不想在您的模型类中设置此选项,您可以通过required option 使其在序列化器类中工作,例如

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

class Meta:
model = Product
fields = '__all__'

关于python - 有没有办法允许 Django 休息框架的空白数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70123477/

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