按日期和日期时间划分的 Django 模型历史记录
Django model history by date and datetime
假设我有这样的模型:
class Account(models.Model):
balance = models.IntegerField()
debt = models.IntegerField()
history = HistoricalRecords()
我正在使用 django-simple-history 获取模型的实例,因为它在提供的日期和时间存在:
inst = Account.history.as_of(datetime.datetime.now().date)
它工作正常,但我想获得一个实例,其中余额字段表示为它在提供的日期和时间存在,然后债务字段将是该日期的最新字段。我不知道这是否可能,没有找到任何相关信息。
历史 ORM 将 return 支持基于您提交的模型的模型,因为它在那个时间点存在。
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() 方法 return 您打算从中读取的历史对象,您可以这样做:
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)
假设我有这样的模型:
class Account(models.Model):
balance = models.IntegerField()
debt = models.IntegerField()
history = HistoricalRecords()
我正在使用 django-simple-history 获取模型的实例,因为它在提供的日期和时间存在:
inst = Account.history.as_of(datetime.datetime.now().date)
它工作正常,但我想获得一个实例,其中余额字段表示为它在提供的日期和时间存在,然后债务字段将是该日期的最新字段。我不知道这是否可能,没有找到任何相关信息。
历史 ORM 将 return 支持基于您提交的模型的模型,因为它在那个时间点存在。
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() 方法 return 您打算从中读取的历史对象,您可以这样做:
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)