T
T
Teslaman2018-06-16 16:32:52
Django
Teslaman, 2018-06-16 16:32:52

How to display the 5 most recent posts sorted by views?

Hi friends. There is a model:

class Article(models.Model):
    ...
    is_published    =   models.BooleanField("Опубликовать?", default=True,)
    pub_date        =   models.DateTimeField("Дата обновления", auto_now_add=True, blank=True, null=True)
    views           =   models.PositiveIntegerField("Просмотры", default=0)

I need to display the last 5 published posts on the main page, sorted by the number of views.
I did this:
# Первый вариант:
article_list = Article.objects.filter(is_published=True).order_by("-pub_date", "-views",)[:5]

# Второй вариант:
article_list = Article.objects.filter(is_published=True).order_by("-views", "-pub_date",)[:5]

Both of these options do not do what I need. In the first case, views have practically no effect on the display order of the list. In the second, the list is sorted by views, but entries from the entire database appear, and not just the last 5.
Help with advice :)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question