How can I use django model method for ordering in meta class

class Post(models.Model):
    title = models.CharField(max_length=255, verbose_name="ady")
    text = RichTextField(verbose_name="text")
    tagList = models.ManyToManyField(Tag, verbose_name="taglar", related_query_name="tagList")
    image = models.ImageField(upload_to="postImage/", verbose_name="surat")
    seen = models.ManyToManyField(UserId,verbose_name="görülen sany", blank=True, related_name="gorulen")
    like = models.ManyToManyField(UserId,verbose_name="like sany", blank=True)
    share = models.PositiveIntegerField(verbose_name="paýlaşylan sany", null=True, blank=True, default="0")
    createdAt = models.DateTimeField(auto_now_add=True, verbose_name="goşulan güni")

    class Meta:
        verbose_name_plural="Makalalar"
        # ordering = ("-createdAt",)
        ordering = ["-hotness",]

    def __str__(self):
        return self.title

    def likes(self):
        return self.like.count()

    likes.short_description = "Like sany"
    likes.allow_tags = True

    def seens(self):
        return self.seen.count()

    seens.short_description = "Görülen sany"
    seens.allow_tags = True

    @property
    def hotness(self):
        return self.likes() + self.seens() + self.share

how can I user hotness function value to ordering in meta class

The hotness property you defined using the @property decorator uses two methods, likes and seens, which are used to return the count of related objects. However, these methods return the count of related objects by calling the count method on the related manager, which returns an integer.

The hotness property should simply return the sum of the count of related objects, rather than calling the likes and seens methods so:

class Post(models.Model):
    # ... other fields ...
    
    @property
    def hotness(self):
        return self.like.count() + self.seen.count() + self.share
    
    class Meta:
        verbose_name_plural="Makalalar"
        ordering = ["-hotness",]
Back to Top