Mossaddak
Mossaddak

Reputation: 421

How can I count overall how many reviews are in an author's all posts?

I building an e-Commerce website, here also has a system of merchandiser accounts. Every merchandiser can upload their product photo with all information for selling. A merchandiser can sell different types of products. Buyers can give product reviews on the product they bought. Now I want to show the overall total of how many buyers have given feedback on seller products. For example: seller-1: 10 reviews, 4.5 star, seller-2: 5 reviews, 4.8 star, seller-3: 11 reviews, 4.1 star. How can I do it? Please help me😢...

models.py:

class Products(models.Model):
    user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True)
    product_title = models.CharField(blank=True, null=True, max_length = 250)
    brand = models.CharField(max_length=250, blank=True, null=True)
    product_desc = RichTextField(blank=True, null=True)


class ProductREVIEWS(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE)
    product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE)
    feedBACK = models.TextField(blank=True, null=True)
    rating = models.IntegerField(blank=True, null=True)

Upvotes: 1

Views: 85

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

You can .annotate(…) [Django-doc] with:

from django.db.models import Count

User.objects.annotate(
    number_of_reviews=Count('merchandise_product_related_name__productREVIEWrelatedNAME')
)

The User objects that arise from this QuerySet will have an extra attribute .number_of_reviews.

Upvotes: 2

Related Questions