【问题标题】:How to reference foreignkeys in history_list_display in django-simple-history?如何在 django-simple-history 的 history_list_display 中引用外键?
【发布时间】:2020-09-29 22:17:33
【问题描述】:

我已将 HistoricalRecords 添加到 django 中的模型中。

我能够使用history_list_display 属性在管理面板的历史记录页面中显示列。

在这些列中,我有可以在 history_list_display 属性元组中使用 employee 显示的员工。但是当我尝试使用 employee__person__person_name 对其他表进行 ForeignKey 引用时,它显示的是 None

如何在 django admin 的历史页面中显示 ForeignKey 参考值?

【问题讨论】:

    标签: django foreign-keys django-admin django-admin-tools django-simple-history


    【解决方案1】:

    django-simple-history 保存对象的历史版本时,它通过删除对其外键的任何外键约束来实现(这样当您删除历史记录指向的对象时,历史记录不受影响) .按照django-simple-history 处理外键的方式进行操作,您无法执行在 django admin 中通常可以执行的双下划线查询类型。相反,您可以自己查询对象,如下所示:

    @register(Employee)
    class EmployeeAdmin(SimpleHistoryAdmin):
        list_display = [...]
        history_list_display = ["get_employee_name", "get_employee_manager_name"]
    
        def get_employee_name(self, obj):
            obj.person.name
    
        def get_employee_manager_name(self, obj):
            return Employee.objects.filter(pk=obj.employee.id).first().manager.person.person_name
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      • 2020-10-10
      • 2020-09-29
      • 2013-01-13
      相关资源
      最近更新 更多