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

2024-06-26 02:04:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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

我找不到从HistoricalChildHistoricalParent的外键。我错过什么了吗?django简单的历史还有其他的作用吗?你知道吗


Tags: djangochildtruefieldsmodelmodelsinvoicehistory
2条回答

因此,让我在使用django-simple-history时中断外键关系

所以HistoricalChild无法获得HistoricalParent的外键

HistoricalChild = apps.get_model('app', 'HistoricalChild')
HistoricalChild.objects.filter(parent_ptr_id=invoice.parent_history.id).order_by('-history_date')

将返回这么多的项目,这对我来说是非常无用的,因为父母有它的状态从某个日期,但孩子是从未来

这意味着我不能在某个时间点通过引用它的历史父代来重建一个完整的子代。。你知道吗

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

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)

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

我不确定这是您想要做的,但是可以通过反向关系访问对象父对象。你知道吗

例如,如果在ParentChild之间有如下清晰的链接:

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(毫不奇怪),但是由于反向关系(检查related_name参数):parent.blabla,也可以从parent访问child。你知道吗

希望有帮助!你知道吗

相关问题 更多 >