首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django简单历史继承从父历史到子历史

Django简单历史继承从父历史到子历史
EN

Stack Overflow用户
提问于 2019-12-25 17:57:02
回答 2查看 809关注 0票数 0

我正在尝试使用django-simple-history来保持对象的状态。

假设我有以下内容:

代码语言:javascript
复制
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

代码语言:javascript
复制
Invoice.objects.get(id=1).parent_history.child

不工作并引发

代码语言:javascript
复制
AttributeError: 'HistoricalParent' object has no attribute 'child'

这就是我从Parent访问Child的方法

代码语言:javascript
复制
Invoice.objects.get(id=1).parent.child

我找不到从HistoricalChildHistoricalParent的外键。我是不是遗漏了什么?django-simple-history还能以其他方式工作吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-25 20:57:02

因此,让我们在使用django-simple-history时打破外键关系

因此HistoricalChild没有获得HistoricalParent外键

代码语言:javascript
复制
HistoricalChild = apps.get_model('app', 'HistoricalChild')
HistoricalChild.objects.filter(parent_ptr_id=invoice.parent_history.id).order_by('-history_date')

我将返回这么多项,这对我来说非常无用,因为父对象有某个特定日期的状态,而子对象来自未来

这意味着我不能通过在某个时间点引用它的历史父级来重新创建一个完整的子级。

我最终使用historical_date重新创建了一个Child实例,如下所示

代码语言:javascript
复制
parent_dict = apps.get_model('order', 'HistoricalParent').objects.filter(history_date__lte=invoice.created_date).order_by('-history_date').values().first()
child_dict = apps.get_model('app', 'HistoricalChild').objects.filter(history_date__lte=invoice.created_date).order_by('-history_date').values().first()

child_dict.update(parent_dict)

for field in ['history_change_reason', 'history_id', 'history_type', 'history_date', 'history_user_id']:
    child_dict.pop(field)

child_from_the_past = Child(**child_dict)
票数 0
EN

Stack Overflow用户

发布于 2019-12-25 19:03:45

错误消息对我来说非常清楚:没有与您的Parent模型关联的child属性。您不能从parent访问child,因为它们之间没有关系(从数据库的角度来看)。从父类继承并不意味着它们之间有任何关系,只是子类将继承父类的属性和方法,仅此而已。

我不确定这是您想要做的事情,但通过反向关系访问对象父对象是可能的。

例如,如果您在ParentChild之间有一个清晰的链接,如下所示:

代码语言:javascript
复制
class Parent(models.Model):
    fields...
    history = HistoricalRecords(inherit=True)

class Child(models.Model):
    fields...
    parent = models.ForeignKey(Parent, blank=True, null=True, on_delete=models.PROTECT, related_name='blabla')

然后,可以按如下方式访问parentchild.parent (这并不奇怪),但是也可以从parent访问子级,这要归功于反向关系(检查related_name参数):parent.blabla

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59477221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档