按日期字段过滤对象?

时间:2017-09-19 21:11:11

标签: python django class object datefield

class Avergae(models.Model):
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    region = ChainedForeignKey(Region, chained_field="state",chained_model_field="state", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    cluster = ChainedForeignKey(Cluster, chained_field="region",chained_model_field="region", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    school = ChainedForeignKey(School, chained_field="cluster",chained_model_field="cluster", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE)
    average_date = models.DateField()
    average = models.DecimalField(max_digits=4, decimal_places=2)
    attendance = models.IntegerField()
    note = models.CharField(max_length=250)

def __str__(self):
    return '{}: {}'.format(self.average_date, self.average)

我想根据日期过滤最新的对象。 需要获取具有属性average_date的最新日期值的对象。 请让我知道语法。 谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用queryset方法latest通过average_date获取最新对象:

obj = Avergae.objects.latest('average_date')