'Fetch queryset with maximum view counts books
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.
Solution 1:[1]
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 NULL
able.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Willem Van Onsem |