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

标签 python django methods model django-simple-history

我正在使用 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/

相关文章:

java - Convention : when writing methods, 应该返回值,还是直接改数据?

python - 如何确定列表中的循环?

django - 过滤查询以获取两个 friend 之间的聊天消息?

Ruby:当类方法就足够时,为什么要实例化一个对象并使用实例方法?

django - 使用 easy-thumbnails 为 Tastypie API 生成缩略图

Django JsonField 按两个字段过滤

methods - abap多方法调用

python - pip 安装 getch : clang error

python - 在字段中添加 "UOM"(测量单位) - OpenErp

python - Pandas 的 .to_string(index=True) 不遵循文档