从管理员外部访问Django简单历史记录?

时间:2016-10-04 08:44:07

标签: django logging django-simple-history

我在项目中使用Django simple history来存储LogEntry。我使用 Django rest framework (DRF)和前端使用Angularjs进行API构建。 保存对象的LogEntry历史记录没有任何问题,如下图所示!

enter image description here

models.py

from datetime import datetime
from django.db import models
from simple_history.models import HistoricalRecords


class Person(models.Model):

    """ Person model"""

    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    workphone = models.CharField(max_length=15, blank=True, default='')
    avatar = models.FileField(upload_to="", blank=True, default='')
    createdtstamp = models.DateTimeField(auto_now_add=True)
    history = HistoricalRecords(inherit=True)


    def __unicode__(self):
        return "%s" % self.first_name

我可以毫无问题地从django admin访问对象历史记录。但, 如何从Django管理员外部访问LogEntry历史记录?我想序列化日志查询集并以json格式返回响应。

到目前为止我所知道和做过什么?

from person.models import Person
from datetime import datetime

>>> person = Person.objects.all()
>>> person.history.all()

2 个答案:

答案 0 :(得分:2)

您可以使用ListView检索数据。

假设您的django-simple-history配置正确,请按照以下步骤操作:

模型 models.py

from django.db import models
from simple_history.models import HistoricalRecords

# Create your models here.

class Poll(models.Model):
    question = models.CharField(max_length=200)
    history = HistoricalRecords()

查看 views.py

from django.shortcuts import render
from django.views.generic import ListView
from .models import Poll

# Create your views here.

class PollHistoryView(ListView):
    template_name = "pool_history_list.html"
    def get_queryset(self):
        history = Poll.history.all()
        return history

模板 pool_history_list.html

<table>
    <thead>
        <tr>
            <th>Question</th>
            <th>History Date/Time</th>
            <th>History Action</th>
            <th>History User</th>
        </tr>
    </thead>
    <tbody>
        {% for t in object_list %}
        <tr>
            <td>{{ t.id }}</td>
            <td>{{ t.question }}</td>
            <td>{{ t.history_date }}</td>
            <td>{{ t.get_history_type_display }}</td>
            <td>{{ t.history_user }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

答案 1 :(得分:0)

制作你自己的历史编组器......

class HistorySerializer(serializers.ModelSerializer):
    class Meta:
        model=Person

然后在你的观点......

class HistoryViewset(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = HistorySerializer

    @list_route(methods=["GET", "POST"])
    def history(self,request):
        var=Person.history.all()
        serialized_data=HistorySerializer(var,many=True)
        return Response(serialized_data.data)