'How to make changes to the database? (DRF)
In the model of the Post object, I have field created = models.DateTimeField field (auto_now_add = True)
There is another field end_time, in which - today's date + 1 month in advance. That is, if a post was created, then it will have today's date in the created field (January 5, 2020), and in the end_time field it will be a month ahead (February 5, 2020).
def next_month():
now = timezone.now()
return now + relativedelta(months=+1)
end_time = models.DateTimeField(default=next_month, blank=True, editable=False)
To all this, I'm need to add the is_actual field, in which -
@property
def is_actual(self):
return bool(self.end_time and self.end_time > now())
But in this case, I can not use the filter to display the fields, where is_actual == true. For me, a filter using this field is very important.
What needs to be done so that I can apply a filter by the is_actual field? As far as I understand, here you need to make once a day, for example, changes to the database. But how? To write some kind of custom script, or to do it somehow using Django methods?
Solution 1:[1]
I would suggest to make "is_actual = model.BooleanField(default=False)" and do what necessary in the clean method. For example:
class MyModel(models.Model):
is_active=models.BooleanField(default=False)
...
def clean(self):
super(MyModel, self).clean()
if self.end_time:
self.is_active = self.end_time > now()
Check here for more insights: https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.clean
Solution 2:[2]
Filter with:
from django.db.models.functions import Now
# is_actual is True
MyModel.objects.filter(
end_time__gt=Now()
)
# is_actual is False
MyModel.objects.filter(
end_time__lte=Now()
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mnislam01 |
| Solution 2 | Willem Van Onsem |
