【发布时间】:2019-12-25 09:57:01
【问题描述】:
我正在尝试使用django-simple-history 来保持对象的状态。
假设我有以下内容:
class Parent(models.Model):
fields...
history = HistoricalRecords(inherit=True)
class Child(Parent):
fields...
class Invoice(models.Model):
fields...
parent_history = models.ForeignKey("app.HistoricalParent", blank=True, null=True, on_delete=models.PROTECT, help_text="This keeps the state of the Child when Invoice is generated")
parent = models.ForeignKey(Parent, blank=True, null=True, on_delete=models.PROTECT) # can be removed so foreign key loop gets eliminated
如何从Invoice 到达Child?
Invoice.objects.get(id=1).parent_history.child
不工作和提高
AttributeError: 'HistoricalParent' object has no attribute 'child'
这就是我从Parent 到达Child 的方式
Invoice.objects.get(id=1).parent.child
我找不到从HistoricalChild 到HistoricalParent 的外键。我错过了什么吗? django-simple-history 是否以其他方式工作?
【问题讨论】:
-
HistoricalParent类的定义是什么? -
@KrazyMax 它由
django-simple-history定义,它与Parent基本相同,加上更多的列,如change_reason, history_id, history_date and histtory_type -
好的。我不明白的是,您的
Child课程。你想让它继承Parent类吗?喜欢拥有与您的Parent类相同的字段吗?你给的名字有些不清楚。读到您,您无法从invoice访问child听起来很正常,因为parent_history没有child字段(parent_history和Parent之间是否存在混淆? -
@KrazyMax 以及
django模型继承保留了从Child到Parent的外键,所以我有从Parent到Child的反向外键。我对django-simple-history的期望相同,但显然HistoricalChild与Parent保持相同的外键而不是HistoricalParent -
实际上这就是你错的地方:当孩子从父母那里继承时,父母和它的孩子之间没有自动创建任何
ForeignKey。您必须为此明确定义关系。此外,如果您希望 2 个类具有共同的属性和方法,我建议创建一个抽象模型(一个 mixin),然后让您的Parent和Child从该 mixin 继承。如果这对你来说是个好主意,我可以编辑我的答案给你看一个例子!
标签: python django django-models django-simple-history