Home > Blockchain >  Fetch queryset with maximum view counts books
Fetch queryset with maximum view counts books

Time:04-12

I have a model

class Book(models.Model):
    title = models.CharField(max_length=500, null=True, blank=True)
    description = RichTextField(null=True, blank=True)
    view_counts = models.IntegerField(null=True, blank=True, default=0)

Each time a user views a book instance in detailed view the view_counts attribute is incremented by 1.

Challenge:

Writting a query that will filter for only two books with highest view counts.

CodePudding user response:

You can .order_by(…) [Django-doc] view_counts in descending order and then obtain the largest two, so:

Book.objects.order_by('-view_counts')[:2]

It is however odd that view_counts is NULLable.

CodePudding user response:

You can use .order_by for view_counts based on Django Doc in asc order and then obtain the latest two, so:

Book.objects.order_by('view_counts')[-2:]
  • Related