Siyanew
Siyanew

Reputation: 602

Get the most top liked post ordered by time in django

models.py:

class Post(models.Model):
    author = models.ForeignKey('User')
    text = models.TextField(max_length=320)
    created_date = models.DateTimeField(default=timezone.now)

class Likes(models.Model):
    post = models.ForeignKey('Post')
    liker = models.ForeignKey('User')
    created_date = models.DateTimeField(default=timezone.now)

    class Meta:
        unique_together = ('post', 'liker')

I want to Get newest posts which their likes are more than 70. how can I write that query set with django orm ?

Upvotes: 0

Views: 691

Answers (2)

Sayse
Sayse

Reputation: 43300

You need to annotate a count of the number of likes then filter on that

Post.objects.annotate(num_likes=Count('likes')).filter(num_likes__gt=70).order_by('-created_date')

Upvotes: 4

Marin
Marin

Reputation: 1121

You can do QV like this example.

qv = Likes.objects.filter(liker__gt = 70).all()
out = Post.objects.filter(id__in=qv).order_by('-created_at')

Upvotes: 0

Related Questions