Как подсчитать отзывы о товаре в django?

Я создаю сайт электронной коммерции на django. В моих моделях у меня есть модель продукта и модель отзывов. Как я должен соединить эти две модели для количества отзывов и атрибута средней оценки?

Это мой текущий файл моделей

class Product(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    brand = models.CharField(max_length=200, null=True, blank=True)
    image = models.ImageField(null=True, blank=True, default='placeholder.png')
    description = models.TextField(null=True, blank=True)
    rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    countInStock = models.IntegerField(null=True, blank=True, default=0)
    id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False)

    numReviews = [Count the number of reviews where product.id matches self.id]

    averageRating = [Sum up the ratings in reviews for this product and divide them by their count]

    def __str__(self):
        return str(self.name)


class Review(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    rating = models.IntegerField(null=True, blank=True, default=0)
    comment = models.TextField(null=True, blank=True)
    createdAt = models.DateTimeField(auto_now_add=True)
    id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False)

    def __str__(self):
        return f'{self.user} review for {self.product}'

Как вы можете видеть, столбцы numReviews и average rating предназначены для связи обеих таблиц. Я безуспешно пытаюсь понять, как правильно это сделать.

Любая помощь будет очень признательна

Я бы сделал их методами модели... Не думаю, что возникнут проблемы с тем, что объект Review определен ниже метода

а для Avg я использовал команду Django aggregate которая заставляет БД делать работу.

models.py

class Product(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    brand = models.CharField(max_length=200, null=True, blank=True)
    image = models.ImageField(null=True, blank=True, default='placeholder.png')
    description = models.TextField(null=True, blank=True)
    rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    countInStock = models.IntegerField(null=True, blank=True, default=0)
    id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False)

    def __str__(self):
        return str(self.name)

    def num_of_reviews(self):
        return Review.objects.filter(product=self).count()

    def average_rating(self):
        from django.db.models import Avg
        return Review.objects.filter(product=self).aggregate(Avg('rating'))['rating__avg']

Использовать

obj = Product.objects.all().first()
obj.num_of_reviews()
obj.average_rating()
Вернуться на верх