Home > OS >  Django Filtering to Get Popular Posts
Django Filtering to Get Popular Posts

Time:09-29

I have two different models. HitCount model stores IP addresses whose was viewed Post. And what i want is filtering popular 3 posts which viewed more. I've tried some queries but i couldn't. I am sharing my models with you.

class Post(ModelMeta, models.Model):

    title = models.CharField(max_length=255, verbose_name='Başlık', unique=True)
    slug = models.SlugField(max_length=255, unique=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts', verbose_name="Yazarı")
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='blog_posts',
                                 verbose_name="Kategorisi", null=True)
    tags = models.ManyToManyField(Tag, related_name='blog_posts', verbose_name='Etiketler')
    image = models.ImageField(verbose_name='Fotoğraf (800x460)')
    content = RichTextField()
    description = models.TextField(null=True)
    status = models.IntegerField(choices=STATUS, default=0, verbose_name='Yayın Durumu')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturulma Tarihi')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Güncellenme Tarihi')
    
    @property
    def get_hit_count(self):
        return HitCount.objects.filter(post=self).count()

class HitCount(models.Model):

    ip_address = models.GenericIPAddressField()
    post = models.ForeignKey("Post", on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.ip_address} => {self.post.title}'

CodePudding user response:

You can try something like this :

most_viewed_posts = Post.objects.all().order_by('-get_hit_count')[3]

I don't think that you can order by 'get_hit_count', but I think those questions can help you : Django order_by a property

Using a Django custom model method property in order_by()

CodePudding user response:

I did what i want with sorted method. Thanks Alexandre Boucard for the resources.

Solution; sorted(Post.objects.filter(status=1), key=lambda a: a.get_hit_count, reverse=True)

reverse=False as a default and it sorts ascending in this case i want to get reversed so i used reverse=True

  • Related