Reputation: 1835
I want to update existing date field in django using existing days field in the same table.
For example
class Sample(models.Model):
notify_status = models.BooleanField(default=0)
next_date = models.DateField(blank=True, null=True)
days = models.IntegerField(blank=True, null=True)
Now I want to add days
to next_date
where next_date
is less than todays date.
I have tried this:
import datetime
from django.db.models import F
Sample.objects.filter(next_date__lt=today).update(next_date=F('next_date')+datetime.timedelta(days=F('days')))
But its not working. Here is the output
Something went wrong in period_retrack.py: unsupported type for timedelta days component: F
Expected Output I want next_date to be increased by the number of days in the same table for every row where next_date is less than current_date i.e, today's date
Upvotes: 1
Views: 1106
Reputation: 840
You can cast the days
field value to an interval at the database level:
import datetime
from django.db.models import CharField, DurationField, F, Value
from django.db.models.functions import Cast, Concat
Sample.objects.filter(next_date__lt=today).update(
next_date=F("next_date")
+ Cast(
Concat("days", Value(" days"), output_field=CharField()),
output_field=DurationField(),
)
)
Notice that I'm doing the cast in 2 steps:
This would work with Postgres, I'm not sure about other databases.
Upvotes: 1