django 简单历史 - 使用模型方法?

use*_*803 5 python django methods model django-simple-history

我正在使用django-simple-historyhttp://django-simple-history.readthedocs.io/en/latest/
我有一个模型,我想将其方法应用于历史实例。例子:

from simple_history.models import HistoricalRecords

class Person(models.Model):
   firstname = models.CharField(max_length=20)
   lastname = models.CharField(max_length=20)
   history = HistoricalRecords()
   def fullName(self):
       return firstname + lastname

person = Person.objects.get(pk=1) # Person instance
for historyPerson in person.history:
    historyPerson.fullName() # wont work.
Run Code Online (Sandbox Code Playgroud)

由于HistoricalPerson类没有继承Person的方法。但使用 Person 方法实际上是有意义的,因为它们共享相同的字段。

有什么解决办法吗?我更喜欢简单的东西,而不是像为历史实例复制模型中的每个方法一样。

小智 0

对于遇到同样问题的其他人,我通过调用历史记录对象上原始类的方法使其工作。因此,对于问题中的示例,解决方案可能是:

for historyPerson in person.history:
    Person.fullName(historyPerson)
Run Code Online (Sandbox Code Playgroud)

这是可行的,因为方法与 Python 中的函数非常相似,只不过当您在实例上调用方法时,该实例会作为该方法的第一个参数隐式传递。所以如果你有这样的课程:

class Foo:
    def method(self):
        ....
Run Code Online (Sandbox Code Playgroud)

正在做

f = Foo()
f.method()
Run Code Online (Sandbox Code Playgroud)

是相同的:

f = Foo()
Foo.method(f)
Run Code Online (Sandbox Code Playgroud)

我不知道为什么simple-history不复制原始模型的方法。原因之一可能是,由于它允许您排除要记录的字段,因此使用原始方法可能没有意义,因为如果方法使用未记录在历史记录中的字段,则该方法可能不起作用。