我正在使用 django-simple-history
:
http://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.
因为 HistoricalPerson 类没有继承 Person 的方法。但是使用 Person 方法实际上是有意义的,因为它们共享相同的字段..
有什么解决办法吗?我更喜欢简单的东西,而不是像为历史实例复制我的模型中的每个方法..
最佳答案
我找到了另一个解决方法(也许只是插件已更新并获得此功能)。它基于文档:adding-additional-fields-to-historical-models
HistoricalRecords
字段接受 bases
参数,该参数设置历史对象将继承的类。但是你不能只在 Person
类描述中设置 bases=[Person]
,因为它还没有初始化。
所以我最终得到了一个抽象类,它被 Person
类和 HistoricalRecords
字段继承。所以这个问题的例子看起来像:
class AbstractPerson(models.Model):
class Meta:
abstract = True
firstname = models.CharField(max_length=20)
lastname = models.CharField(max_length=20)
def fullName(self):
return firstname + lastname
class Person(AbstractPerson):
history = HistoricalRecords(bases=[AbstractPerson])
现在历史对象可以使用fullName
方法。
关于python - django 简单历史 - 使用模型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237704/