我正在尝试使用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还能以其他方式工作吗?
发布于 2019-12-25 20:57:02
因此,让我们在使用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-25 19:03:45
错误消息对我来说非常清楚:没有与您的Parent模型关联的child属性。您不能从parent访问child,因为它们之间没有关系(从数据库的角度来看)。从父类继承并不意味着它们之间有任何关系,只是子类将继承父类的属性和方法,仅此而已。
我不确定这是您想要做的事情,但通过反向关系访问对象父对象是可能的。
例如,如果您在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 (这并不奇怪),但是也可以从parent访问子级,这要归功于反向关系(检查related_name参数):parent.blabla。
希望这能有所帮助!
https://stackoverflow.com/questions/59477221
复制相似问题