Skip to content
Advertisement

How to get the most liked users on a particular date in django

So I have a social media app, where users can like the posts of other users. Now I fetch the top 20 users who have received the most number of likes. Everything is perfect. But the problem is I cant figure out , how I can fetch the top users who have received the most likes on a particular date, for example get the top users who received most likes only today

My LIKES MODEL

class PostLike(models.Model):
    user_who_liked = models.ForeignKey(User, on_delete=models.CASCADE)
    post_liked = models.ForeignKey(Post, on_delete=models.CASCADE)
    liked_on = models.DateTimeField(default=timezone.now)

SIMPLIFIED POST MODEL

class Post(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='author')
    caption = models.TextField()
    date = models.DateTimeField(default=timezone.now)
    likes = models.ManyToManyField(
        User, blank=True, through=PostLike)
    image = models.TextField()

    class Meta:
        ordering = ['-id']

SIMPLIFIED USER MODEL

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    user_name = models.CharField(max_length=100, unique=True)
    date = models.DateTimeField(default=timezone.now)
    profile_picture = models.TextField(
        default="https://www.kindpng.com/picc/m/24-248253_user-profile-default-image-png-clipart-png-download.png")
    bio = models.CharField(max_length=200, default="")
    objects = CustomManger()

    def __str__(self):
        return self.user_name

** My query to get the top users who received the most number of likes **

users = User.objects.annotate(num__liked=Count('author__likes')).order_by('-num__likes')[:20]

# So everything is perfect and I am getting the users, now I dont know how to get the top users with most likes on a PARTICULAR DATE, for example today

** My try to get the top users with most likes on a particular day**

from django.db.models import Count, Q
from django.utils.timezone import datetime

users = User.objects.annotate(num__liked=Count('author__likes',filter=Q(author__likes__liked_on = datetime.today()))).order_by('-num__likes')[:20]

But with the above query , I cant achieve it. I am getting the error: Related Field got invalid lookup: liked_on

I am pretty sure, I am doing something wrong with the many-many fields.

Advertisement

Answer

Q(author__likes__liked_on = datetime.today()) won’t work, because liked_on is a datetime, while datetime.today() is a date. And the filtered field is on the ‘through’ table.

So you need to cast liked_on to a date, and look up the field on postlike (lower-cased by default):

Q(author__postlike__liked_on__date = datetime.today()))

3 People found this is helpful
Advertisement