【问题标题】:DJANGO - simple-history - how to look up history table from base model using standard django ORM lookupDJANGO - simple-history - 如何使用标准 django ORM 查找从基本模型中查找历史表
【发布时间】:2018-08-07 13:30:37
【问题描述】:

这可能是一个简单的答案,但我找不到关于该主题的可靠“是”或“否”。我正在使用 Django simple-history 并且我正在尝试通过历史表中的信息过滤基本模型对象。因为 simple-history 会自动生成历史表,而我本身并没有为它创建历史模型,所以我不知道 django ORM 查找语法是否在这里有效。我的表关系看起来像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 对象。举个例子;只有历史表中有一个名为“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”没有模型,只是通过用户链接到原始表?

【问题讨论】:

  • 这不应该是filter(repairformhistory__history_change_reason='some reason')(带两个下划线)吗?
  • 确认,是的,你的权利。同样的问题,但这个错误现在更有意义了。

标签: django django-simple-history


【解决方案1】:

从历史模型到基础模型的外键默认存在,因为历史表包含基础模型中包含的所有字段。但是,由于 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)

【讨论】:

    【解决方案2】:

    试试

    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)
    

    【讨论】:

    • 虽然返回历史记录对象。我想要 RepairForm 对象。
    • 你可以使用这个对象来获取父对象。可能有一种方法可以在单个查询中完成,但我不确定。这种方式可行,但可能不是最有效的
    猜你喜欢
    • 2014-08-04
    • 2020-10-10
    • 2020-09-29
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多