Django selects model objects based on time at intervals on the model itself

I am trying to retrieve all expired objects for a model in a Django application.

The model is as follows:

MyModel(models.Model):
    owner = models.ForeignKey(User)
    last_check = models.DateTimeField(blank=True, null=True)
    interval = models.IntegerField(default=1800)

I need to get all suitable objects where last_check is earlier than now minus the control interval to determine if the object should be checked again.

No problem if I use static spacing:

time_diff = datetime.now() - timedelta(seconds=1800)
MyModel.object.filter(last_check__lte=time_diff)

But when the interval is on the model itself, I cannot figure out how to do this. This is what I tried:

objects_to_check = MyModel.objects.filter(
                                        last_check__isnull=False
                                    ).filter(
                                        last_check__lte=datetime.now() - timedelta(seconds=F('interval'))
                                    )

But it didn’t work at all, only I got the following error

unsupported type for timedelta seconds component: F

Any idea how to solve this?

+3
source share
3 answers

Hm... , , . , timedelta .

, ... , , . , last_check expired, :

MyModel.objects.filter(expired__lte=current_date)

:

def save(self):
    self.expired = datetime.now() + self.interval;

- .

+3

F SQL-, Python . extra Python:

filter(lambda x: x.last_check <= datetime.now() - timedelta(seconds = x.interval), MyModel.objects.all())
0

Source: https://habr.com/ru/post/1722863/


All Articles