This is my models and I defined set null=True, blank=True for foreign key relations but when I hit my API then API response raised that { "product": [ "This field is required."] }. What I wrote wrong. please help me.
Here is my model:
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"
Here is my views:
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)
And here is my Serializers:
class WriteCashSellSerializer(serializers.ModelSerializer):
product = serializers.SlugRelatedField(slug_field='id', queryset=Product.objects.all())
class Meta:
model = CashSell
fields = '__all__'
CodePudding user response:
Define your serializer like this
class WriteCashSellSerializer(serializers.ModelSerializer):
product = serializers.SlugRelatedField(slug_field='id', queryset=Product.objects.all(), required=False)
class Meta:
model = CashSell
fields = '__all__'
You are redefinining field in serializer so you need to add required=False
flag.