Nerd
Nerd

Reputation: 285

adding additional fields to serializer from another model

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

Upvotes: 5

Views: 4169

Answers (2)

Jaskaran Singh
Jaskaran Singh

Reputation: 169

The issue is with the query. Instead of

# comparing it with wishlist pk instead of wishlist's pro
Review.objects.filter(product_id=obj.id).count()

but it should get the products review

def get_review(self, obj):
    return Review.objects.filter(product_id=obj.product.id).count()

Upvotes: 1

hancho
hancho

Reputation: 1437

I would use .annotate

from django.db.models import Count

WishList.objects.annotate(review_count=Count('product__review_set')

Check what the related name is for review on product but it should be review_set if you did not define it.

Then add 'review_count' to WishListSerializer fields.

review_count = serializers.IntegerField(required=False)

You'd annotate onto the queryset in the ViewSet. I'd overwrite get_queryset

Upvotes: 0

Related Questions