Reputation: 1270
I am building a BlogApp and I am stuck on a Problem.
What i am trying to do:-
I am trying to access only BlogPosts
which are posted in last two days and got most views.
models.py
class BlogPost(models.Model):
blog_post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE)
date_added = models.DateTimeField(null=True,default=timezone.now)
viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_blog_posts',editable=False)
views.py
def viewd_post(request):
d = timezone.now() - timedelta(days=2)
posts = BlogPost.objects.annotate(total_views=Count('viewers')).filter(date_added__gte=d).order_by('-total_views')
context = {'posts':posts}
return render(request, 'most_views.html', context)
What have i tried :-
I also tried annotate method to get most viewed post, It works perfectly like : it shows most viewed blogpost at top but it shows all the posts which are posted in last two days and got no views.
Any help would be Appreciated.
Thank You in Advance.
Upvotes: 1
Views: 404
Reputation: 476813
You can exclude items with no views with:
posts = BlogPost.objects.annotate(
total_views=Count('viewers')
).filter(
date_added__gte=d, total_views__gt=0
).order_by('-total_views')
Upvotes: 1