Django:根据另一个字段/列获取字段/列的对象?

时间:2014-09-04 03:56:10

标签: mysql django

是否可以获取具有与同一对象的另一个字段相关的字段的对象?

例如,我想这样做:

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)

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

对于简单的日期时间表达式,您可以使用F过滤器: https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

来自docs:

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

如果您的过滤器涉及复杂表达式,建议您使用extra子句:https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra

当然,如果您确定自己的数据库后端,这种方法很有效。