1

Is it possible to get an object with a field that is related to another field of the same object?

For example I'd like to do:

class Transfer(models.Model):
    creation_time=models.IntegerField(default=0)
    ttl=models.IntegerField(default=600)

alive_transfers = Transfer.objects.filter(creation_time__gt=time.time()-ttl)
1

2 Answers 2

0

For simple datetime expressions you can use F filters: https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

From docs:

>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))

If your filter involves a complex expression, I suggest using extra clause: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra

Of course this works well if you are sure about your DB backend.

0
#If you want to save that field, override the save method, something like this
class Transfer(models.Model):
    creation_time = models.IntegerField(default=0)
    ttl = models.IntegerField(default=600)
    alive_transfers = models.IntegerField()   

    def save(self, *args, **kwargs):
        self.alive_transfers = self.creation_time__gt=time.time()-self.ttl
    super(Transfer, self).save(*args, **kwargs) # Call the "real" save() method.


# If you want just get without saving, make an instance method to call in the views
class Transfer(models.Model):
    creation_time = models.IntegerField(default=0)
    ttl = models.IntegerField(default=600)

    def _get_alive_transfers(self):
        return self.creation_time__gt=time.time()-self.ttl


# so in the views you call that method in an object instance, example:
alive_transfers = Transfer.objects.filter(pk=1)._get_alive_transfers()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.