首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可以使用django-simple-history创建一个包含所有历史记录的序列化程序吗?

可以使用django-simple-history创建一个包含所有历史记录的序列化程序吗?
EN

Stack Overflow用户
提问于 2019-09-12 22:11:14
回答 2查看 667关注 0票数 0

我正在使用django-simple-history在我的模型中记录活动。我的想法是有一个序列化程序来聚合模型的所有活动,并有一个视图来显示带有过滤器的信息(每个模型和用户)。

像这样的...api/history/?table=example&user=2...api/history/?table=another_example

模型

代码语言:javascript
复制
class MyExampleModel(models.Model):
    ...
    history = HistoricalRecords()

class MyAnotherExampleModel(models.Model):
    ...
    history = HistoricalRecords()

串行器

代码语言:javascript
复制
class HistorySerializer():
    # with all records activities

视图

代码语言:javascript
复制
class HistoryViewSet():
    # with filter for model and user.
EN

回答 2

Stack Overflow用户

发布于 2019-09-13 02:57:10

是的,你可以这样做。这只是一个您想要在序列化程序中包含什么数据以及您想要进行多少数据库查询的问题。

每个模型的历史记录保存在一个单独的表中,因此如果您有n个表,则需要n个查询。为了找到您需要查询的所有管理器,您可以在视图中运行以下代码块:

代码语言:javascript
复制
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,并且:

代码语言:javascript
复制
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_id
  • history_id
  • change_reason
  • history_date
票数 1
EN

Stack Overflow用户

发布于 2020-02-19 00:26:35

您应该尝试使用django.apps.apps.get_models()。表模式是“历史MyExampleModel”

代码语言:javascript
复制
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())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57908614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档