0

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

我怎样才能到达从InvoiceChild

Invoice.objects.get(id=1).parent_history.child

不工作和提高

AttributeError: 'HistoricalParent' object has no attribute 'child'

这就是我ChildParent

Invoice.objects.get(id=1).parent.child

我找不到 to 的外HistoricalChildHistoricalParent。我错过了什么吗?django-simple-history 是否以其他方式工作?

4

2 回答 2

0

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

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

例如,如果您在以下内容之间有明确的Parent联系Child

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')

那么,parent可以按如下方式访问:(不足为奇),但是由于反向关系(检查参数)child.parent,也可以访问child :.parentrelated_nameparent.blabla

希望有帮助!

于 2019-12-25T11:03:45.430 回答
0

所以让我在使用时打破外键关系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)
于 2019-12-25T12:57:02.150 回答