2016-10-04 72 views
0

我在我的項目中使用Django simple history來存儲LogEntry。我有使用Django rest框架(DRF)和前端使用Angularjs的API版本。 保存對象的LogEntry歷史記錄沒有任何問題,如下圖所示!訪問Django從admin以外的簡單歷史記錄?

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管理訪問對象歷史記錄沒有任何問題。但是, 如何從Django管理員訪問LogEntry歷史以外的內容?我想序列化日誌queryset並以json格式返回響應。

我到目前爲止所瞭解和完成的工作?

from person.models import Person 
from datetime import datetime 

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

這聽起來像一個代碼,這對我來說,問題ATM。請儘量加上你的最大努力 – e4c5

+0

我修改了我的最佳@ e4c5! – MysticCodes

回答

0

使自己historyserializer這樣的...

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) 
0

您可以通過使用一個ListView檢索數據。

假設你的Django簡單的歷史記錄被正確配置,按下列程序辦理:

型號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> 
相關問題