Home > front end >  How can I calculate Position based on another field of Django model instances?
How can I calculate Position based on another field of Django model instances?

Time:06-10

I have a Django model that looks like this:

class Image(models.Model):
    name = models.CharField(max_length=60)
    description = models.CharField(max_length=60, null=False)
    clicks = models.IntegerField(default=0)
    views = models.IntegerField(default=0)

    @property
    def weight(self) -> float:
        return round((self.clicks * 0.7   self.views * 0.3), 2)

Based on weight, I'd like to estimate a position field of Image. It should give a position based on weight of all instances of Image. The higher the weight, the higher the position (position 1 - highest weight, position 2 - second highest, etc.)

How can I create a function that would take ALL the Image instances I have in the DB and calculate position for all of them?

CodePudding user response:

You can use a window function to calculate the position of each Image by using RowNumber

from django.db.models import Window, F
from django.db.models.functions import RowNumber


images_with_position = Image.objects.annotate(
    weight=F('clicks') * 7   F('views') * 3
).annotate(
    position=Window(expression=RowNumber(), order_by=F('weight').desc())
)
  • Related