按日期字段过滤对象?
Filtering object by 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 的最新日期值的对象。
请让我知道语法。
谢谢。
您可以使用查询集方法 latest 通过 average_date
获取最新对象:
obj = Avergae.objects.latest('average_date')
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 的最新日期值的对象。 请让我知道语法。 谢谢。
您可以使用查询集方法 latest 通过 average_date
获取最新对象:
obj = Avergae.objects.latest('average_date')