Multiplying the difference between today and a DateField by a number using Django Models

20 views Asked by At

I'm trying to get the difference in days between

  1. the date each row of my table
  2. The current date So I can then multiply it by a number. However I keep getting errors and exceptions. I searched Google, the Django docs, but couldn't find how. I even asked ChatGPT and Codeium but they keep giving completely wrong advice and direction.

If I over-simplify my model and query, There is the History table with all the rows containing the symbols, their type and their rank on a specific date.

class History(models.Model):
    date = models.DateField()
    type = models.CharField(max_length=255, choices=["type1", "type2", "type3"])
    symbol = models.CharField(max_length=10)
    rank = models.PositiveSmallIntegerField()
    rating = models.DecimalField(max_digits=3, decimal_places=2)

Then with this query, I'm trying to get all the rows of "type1", then getting the difference in days between today and their date to multiply this amount by their rank:

compiled_type = (
    History.objects
    .values("symbol", "type")
    .filter(type="type1")
    .annotate(days_difference_delta=datetime.now().date() - F('date')) # This works and returns a TimeDelta
    .annotate(score=ExpressionWrapper((datetime.now().date() - F('date')) * F('rank')), output_field=IntegerField) # Getting a ton of errors and exceptions whatever I put on this line
    .order_by("-score").all()
)

Again it's over-simplifying as this is just the first step of a more complex calculation where I would group all rows by their symbol and Sum()all the scores, but I'm trying to make this simple query work first. I tried without theExpressionWrapper, I tried setting the output_fieldtoDecimalField, DateField, DurationField`, etc etc. But I have no idea what I'm doing and it seems like the Django docs is not really explaining much how this works.

So how can I multiply a TimeDelta to a number? Or how can I multiply a number by the days between 2 dates?

0

There are 0 answers