我正在使用django-simple-history在我的模型中记录活动。我的想法是有一个序列化程序来聚合模型的所有活动,并有一个视图来显示带有过滤器的信息(每个模型和用户)。
像这样的...api/history/?table=example&user=2,...api/history/?table=another_example
模型
class MyExampleModel(models.Model):
...
history = HistoricalRecords()
class MyAnotherExampleModel(models.Model):
...
history = HistoricalRecords()串行器
class HistorySerializer():
# with all records activities视图
class HistoryViewSet():
# with filter for model and user.发布于 2019-09-13 02:57:10
是的,你可以这样做。这只是一个您想要在序列化程序中包含什么数据以及您想要进行多少数据库查询的问题。
每个模型的历史记录保存在一个单独的表中,因此如果您有n个表,则需要n个查询。为了找到您需要查询的所有管理器,您可以在视图中运行以下代码块:
from simple_history.exceptions import NotHistoricalModelError
from simple_history.utils import get_history_manager_for_model
from django.db import models
history_managers = []
for model in models.registered_models.values():
# If you want to filter by which model you see, you could do that here.
try:
history_managers.append(get_history_manager_for_model(model))
except NotHistoricalModelError:
continue现在,有了history_managers列表,您现在可以创建一个过滤的历史对象列表,并将其传递给序列化程序(假设此时您有一个要过滤的user_id,并且:
history_objects = []
for manager in history_managers:
history_objects += list(manager.objects.filter(history_user_id=user_id))
serializer = MyHistorySerializer(history_objects, many=True)就如何构造序列化程序而言,您需要仅使用在所有历史对象中都一致的序列化程序字段,例如:
history_user_idhistory_idchange_reasonhistory_date发布于 2020-02-19 00:26:35
您应该尝试使用django.apps.apps.get_models()。表模式是“历史MyExampleModel”
from django.apps import apps
class HistoryListApi(generics.ListAPIView):
history_managers = []
for model in apps.get_models():
if 'Historical' in model._meta.object_name:
history_managers.append(model)
history_objects = []
for manager in history_managers:
history_objects += list(manager.objects.all())https://stackoverflow.com/questions/57908614
复制相似问题