0

这可能是一个简单的答案,但我在这个主题上找不到可靠的“是”或“否”。我正在使用 Django simple-history,我试图通过历史表中的信息过滤基本模型对象。因为 simple-history 会自动生成历史表,而我本身并没有为其创建历史模型,所以我不知道 django ORM 查找语法是否在这里有效。我的表关系看起来像这样。这是模型:

class RepairForm(models.Model):
user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING,)
return_number = models.CharField(max_length=200, unique=True)
incident = models.CharField(max_length=100, blank=True)
...
# Simple-history
history = HistoricalRecords()

我正在尝试按历史记录过滤 RepairForm 对象。举个例子; 只有历史表中有一个名为“history_change_reason”的字段。它只是一个用于保存(理想情况下)描述更新发生原因的字符串的字段。参考我链接的表图像,我想我可以通过遍历它们与用户表的关系来使用 RepairFormHistory 表过滤掉 RepairForm 对象。就像是:

RepairForm.objects.filter(user_id__repairformhistory__history_change_reason='Custom Repair form page')

“repairformhistory”是我对历史模型(如果有的话)的最佳猜测。错误:

 Related Field got invalid lookup: repairformhistory

我在这里离基地很远吗?我可以穿越这样的关系吗?即使“repairformhistory”没有模型,只是通过用户链接到原始表?

4

2 回答 2

2

默认情况下存在从历史模型到基本模型的外键,因为历史表包含基本模型中包含的所有字段。但是,由于 key 仅作为整数或 uuid 复制,因此 db 不知道这是一个外键。我们目前在历史模型上有实例属性,它返回历史实例的基本模型实例版本——但这应该只适用于特定实例。我建议在这里做的是查询你想要的 id 的历史表,然后使用这些键过滤基本模型,如下所示:

ids = list(HistoricalRepairForm.filter(incident='abc').order_by('id').distinct('id').values_list('id', flat=True))
RepairForm.filter(id__in=ids)
于 2018-08-13T14:29:11.180 回答
1

尝试

history = RepairForm.history.filter(history_change_reason='Custom Repair form page').first()

或包含一个 user_id

history = RepairForm.history.filter(history_change_reason='Custom Repair form page', history_user_id=user_id).first()

然后使用这个id获取父对象

# check that there is a result
if history:
    # get related object
    Repairs = RepairForm.objects.filter(pk=history.pk)
于 2018-08-07T14:39:47.647 回答