user8557845
user8557845

Reputation:

Django Querying the Database

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 :)

Upvotes: 0

Views: 29

Answers (1)

Alex
Alex

Reputation: 1262

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.

Upvotes: 3

Related Questions