0

假设我有这样的模型:

class Account(models.Model):
    balance = models.IntegerField()
    debt = models.IntegerField()
    history = HistoricalRecords()

我正在使用 django-simple-history 来获取模型的实例,因为它在提供的日期和时间已经存在:

inst = Account.history.as_of(datetime.datetime.now().date)

它工作正常,但我想获得一个实例,其中余额字段表示为在提供的日期和时间存在,然后债务字段将是该日期的最新字段。我不知道这是否可能,没有找到任何相关信息。

4

1 回答 1

1

历史 ORM 将根据您提交的模型返回一个模型,因为它在那个时间点存在。

account = Account.objects.create(balance=1, debt=1)
account.save()
history_obj = account.history.last()
print(history_obj.debt)  # returns 1

account.debt = 222
account.save()
new_history_obj = account.history.last()
print(new_history_obj.debt)  # returns 222

假设您使用 Account.history.as_of() 方法返回您打算从中读取的历史对象,您可以这样做:

yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
history_obj = Account.history.as_of(yesterday)
print(history_obj.debt)  # returns not the current debt, but the debt as-of yesterday

除非我误解了您希望完成的任务,否则您可以使用问题中的内容来执行此操作:

inst = Account.history.as_of(datetime.datetime.now().date)
print(inst.debt)
于 2018-01-24T22:11:11.253 回答