Answer the question
In order to leave comments, you need to log in
How can I filter posts by rating?
I have several models
class RaringStar(models.Model):
value = models.IntegerField('star')
def __str__(self):
return str(self.value)
class Article(models.Model):
article_title = models.CharField('Title', max_length = 200)
article_text = models.TextField('TEXT', null=True, blank=True)
class Raring(models.Model):
star = models.ForeignKey(RaringStar, on_delete=models.CASCADE)
post = models.ForeignKey(Article, on_delete=models.CASCADE)
ip = models.CharField('ip', max_length = 200)
a = Article.objects.filter(raring__isnull=False)
for x in a:
obj = {}
x.raring_set.order_by('-val')
val = 0
for y in x :
val + x.star
obj['val.sum'] = {'title':x.article_title,'val_sum':val}
obj.order_by('-val_sum')
Answer the question
In order to leave comments, you need to log in
In order not to "call all objects several times" or not to do it every time in count queries with related tables, denormalization is used. The Article adds a field with the current rating value, which is recalculated every time someone changes the rating (via save or signals).
PS do not need to call the article_title, article_text fields like that, you just need title and text
Of course, it’s better to denormalize, but if you need it right on the fly, then here :
Article.objects.annotate(avg_rating=Avg('rating__star')).filter(avg_rating__gte=3)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question