I am going to include Model to another serilializer in my project here is the specification. I have a Review model as follows
class Review(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
rating= models.ForeignKey(ProductRating, on_delete=models.DO_NOTHING)
comment = models.TextField()
my function is to show number of comment that users wrote for the product and I should show in serializer like that
class WishList(models.Model):
user = models.ForeignKey('authentication.User', on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
serailzier.py
class GetWishlistSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='product.name', read_only=True)
rating = serializers.IntegerField(source='product.rating', read_only=True)
image = serializers.ImageField(source='product.image', read_only=True)
price = serializers.DecimalField(source='product.price', decimal_places=2, max_digits=10, read_only=True)
review = SerializerMethodField()
class Meta:
model = WishList
fields = ['user','product', 'name', 'rating', 'image', 'price', 'description', 'review']
def get_review(self, obj):
return Review.objects.filter(product_id=obj.id).count()
and it should count the number of review for specified product but it did not work it gives result like that.
{
"user": 1,
"product": 1,
"name": "Samsung A70",
"rating": 5,
"image": "http://localhost:8000/media/products/2019/08/30/wkl6pb_E2RUzH6.jpeg",
"price": "2500.00",
"description": "bla bla bla",
"review": 0
}
but I have one review for product: 1 it should show 1 but it shows 0 I do not know what I am missing here. Any help please? If question is unclear please let me know I will try to specify in more detail