{ "product": [ "This field is required."] } 在 Django REST API

{ "product": [ "This field is required."] } in Django REST API

这是我的模型,我为外键关系定义了 set null=True, blank=True 但是当我点击我的 API 然后 API 响应提出了 { “产品”:[ “此字段是必需的。”] }。我写错了什么。请帮助我。

这是我的模型:

class CashSell(models.Model):
    user_profile = models.ForeignKey('accounts.UserProfile', on_delete=models.CASCADE)
    product = models.ForeignKey('inventory.Product', on_delete=models.CASCADE, related_name='cash_sell', null=True, blank=True)
    cash_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    description = models.CharField(max_length=250)
    date = models.DateField()
    picture = models.ImageField(upload_to='cash_sell_pics', blank=True, null=True, default='images.png')

    def __str__(self):
        return self.user_profile.first_name

    class Meta:
        verbose_name = "Cash Sell"
        verbose_name_plural = "Cash Sell"

以下是我的看法:

class CashSellViewSet(viewsets.ModelViewSet):
    queryset = CashSell.objects.all()
    serializer_class = ReadCashSellSerializer
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action in ('list', 'retrieve'):
            return ReadCashSellSerializer
        return WriteCashSellSerializer

    def get_queryset(self):
        """Only show user related items."""
        return CashSell.objects.filter(user_profile__id=self.request.user.id)

这是我的序列化程序:

class WriteCashSellSerializer(serializers.ModelSerializer):
    product = serializers.SlugRelatedField(slug_field='id', queryset=Product.objects.all())

    class Meta:
        model = CashSell
        fields = '__all__'

像这样定义序列化程序

class WriteCashSellSerializer(serializers.ModelSerializer):
    product = serializers.SlugRelatedField(slug_field='id', queryset=Product.objects.all(), required=False)

    class Meta:
        model = CashSell
        fields = '__all__'

您正在序列化程序中重新定义字段,因此您需要添加 required=False 标志。