简体   繁体   English

Django模型属性引用任意模型实例

[英]Django model attribute to refer to arbitrary model instance

I'm working on a logging app in Django to record when models in other apps are created, changed, or deleted. 我正在Django中使用日志记录应用程序,以记录何时创建,更改或删除其他应用程序中的模型。 All I really need to record is the user who did it, a timestamp, a type of action, and the item that was changed. 我真正需要记录的是执行此操作的用户,时间戳,操作类型以及更改的项目。 The user, timestamp, and action type are all easy, but I'm not sure what a good way to store the affected item is beyond storing an id value and a class name so the item can be retrieved later. 用户,时间戳和操作类型都很容易,但是我不确定除了存储id值和类名之外,存储受影响项的一种好方法是什么,以便以后可以检索该项。 I imagine that storing the class name will result in a bit of a hacky solution in order to find the actual class, so I'm wondering if there's a better way. 我以为存储类名会导致一些棘手的解决方案,以便找到实际的类,所以我想知道是否有更好的方法。 Does anyone know of one? 有人知道吗?

Use generic relations which do just that (use instance id and model class) but are integrated in Django and you also get a shortcut attribute that returns related instance so you don't have to query it yourself. 使用仅执行此操作的通用关系 (使用实例ID和模型类),但已集成在Django中,并且您还获得了返回相关实例的快捷方式属性,因此您不必自己查询它。 Example usage . 用法示例

检查通用关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM