F
F
fantom_ask2020-08-07 08:52:53
Django
fantom_ask, 2020-08-07 08:52:53

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)

i have read
the docs https://docs.djangoproject.com/en/3.0/topics/db/qu...
https://docs.djangoproject.com/en/3.0/ref/models/q...

but i am so and did not understand how to display models by rating

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')


So that I would not have to call all the objects several times and then convert the new object and apply sorting to it, since there are a lot of unnecessary actions

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2020-08-07
@bacon

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

S
Sergey Tikhonov, 2020-08-07
@tumbler

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)

And yes, you will have to correct typos and inconsistencies with your models)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question