加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:12:06 所属栏目:Python 来源:网络整理
导读:我正在使用 django-simple-history: http://django-simple-history.readthedocs.io/en/latest/ 我有一个模型,我想在历史实例上应用它的方法.例: from simple_history.models import HistoricalRecordsclass Person(models.Model): firstname = models.Char
我正在使用 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方法实际上是有意义的,因为它们共享相同的字段.

对此有何解决方案?我更喜欢简单的东西,而不是像我的模型中为历史实例复制每个方法.

解决方法

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

for historyPerson in person.history:
    Person.fullName(historyPerson)

这是有效的,因为方法与Python中的函数非常相似,只是当您在实例上调用方法时,实例将作为方法的第一个参数隐式传递.所以如果你有一个类:

class Foo:
    def method(self):
        ....

f = Foo()
f.method()

是相同的:

f = Foo()
Foo.method(f)

我不知道为什么简单历史不会复制原始模型的方法.一个原因可能是因为它允许你使用exclude fields to be recorded,所以原始方法可能没有意义,因为如果一个方法使用未记录在历史记录中的字段,则该方法可能不起作用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读