0

Here's my Answer Model,

class Answer(models.Model):
    likes = models.ManyToManyField(User, related_name='answer_likes')
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

I wants to filter out the Answers which received Maximum likes in last 24 Hours. How can I do that in view?

Thank You :)

1 Answer 1

3

You need django aggregation api. Try:

from datetime import *
from django.db.models import Count

last_24 = datetime.now() - timedelta(hours = 24)

ans = Answer.objects.filter(timestamp__gte = last_24).annotate(counted_likes = Count('likes')).order_by('-counted_likes')

Now you can ans[0].counted_likesto find out how many likes answer ans[0] have, and order_by term up there assures to you that this first element has the largest number of likes.

See aggregation in django docs for further explanations.

Sign up to request clarification or add additional context in comments.

1 Comment

Working Perfectly fine :) Thank You Sir :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.