DJANGO - simple-history - 如何使用标准 django ORM 查找从基本模型中查找历史记录 table

DJANGO - simple-history - how to look up history table from base model using standard django ORM lookup

这可能是一个简单的答案,但我找不到关于该主题的可靠 "yes" 或 "no"。我正在使用 Django simple-history and I am trying to filter the base model objects by information in the history table. Because simple-history generates the history table automatically, and I didn't create a history model for it per-se I dont know if the django ORM lookup syntax works here. My table relations look like this。这是模型:

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 对象。举个例子;只有历史 table 中有一个名为 "history_change_reason." 的字段,它只是一个用于保存(理想情况下)描述更新发生原因的字符串的字段。参考我链接的 table 图片,我想我可以使用 RepairFormHistory table 通过遍历它们与用户 table 的关系来过滤 RepairForm 对象。类似于:

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

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

 Related Field got invalid lookup: repairformhistory

我离基地远了吗?我可以穿越这样的关系吗?即使 "repairformhistory," 没有模型,只是 table 通过用户链接到原始模型?

尝试

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)

默认情况下存在从历史模型到基本模型的外键,因为历史 table 包含基本模型中包含的所有字段。但是,由于键仅作为整数或 uuid 复制,数据库不知道这是外键。我们目前在历史模型上有实例属性,returns 历史实例的基础模型实例版本——但这只适用于特定实例。我建议在这里做的是查询历史 table 以获取您想要的 ID,然后使用这些键过滤基本模型,如下所示:

ids = list(HistoricalRepairForm.filter(incident='abc').order_by('id').distinct('id').values_list('id', flat=True))
RepairForm.filter(id__in=ids)