I want to display the average rating on a product in the form of stars where i want to have 5 stars and then fill the stars with gold color on how much the average rating on the product is.
This is my code and my relation b/w models
class Product(models.Model):
name = models.CharField(max_length=300)
price = models.DecimalField(max_digits=7, decimal_places=2)
image_url = models.CharField(max_length=400)
digital = models.BooleanField(blank=False)
sizes = models.ManyToManyField(Size, through='ProductSize')
quantity = models.IntegerField(default=1)
def __str__(self):
return self.name
@property
def get_average_rating(self):
average = self.comment_set.aggregate(Avg('rating'))['rating__avg']
if average is not None:
return round(average, 1)
else:
return 0
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField()
image = models.ImageField(upload_to='images/comment_images', null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)])
I tried to run a loop like this but it did not work as the average rating is in float
I do not know much javascript so if you can help me in js that will be appreciated too thank you!!
{% for _ in product.get_average_rating %}
★
{% endfor %}
New contributor
Raja Shirjeel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.