简体   繁体   English

如何从Django恢复对象访问评论和用户

[英]How to access comments and user from django reversion object

How can I access comments and user from an reversion object? 如何从还原对象访问评论和用户?

to create a reversion I use this 创建一个版本,我用这个

with transaction.atomic():
    with reversion.create_revision():
        reversion.set_user(request.user)
        reversion.set_comment("update event")
        form.save()

Now I want to access the user and comment ... I tried: 现在,我想访问用户并发表评论...我尝试了:

import reversion
revs = reversion.models.Version.objects.all()
rev1 = revs[0]
dir(rev1)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__',
'__dict__', '__doc__', '__eq__', '__format__', '__getattribute__',
'__hash__', '__init__', u'__module__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '__unicode__', '__weakref__', '_base_manager',
'_default_manager', '_deferred', '_do_insert', '_do_update',
'_field_dict_cache', '_get_FIELD_display',
'_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order',
'_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks',
'_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val',
'_state', 'clean', 'clean_fields', 'content_type', 'content_type_id',
'date_error_message', 'delete', 'field_dict', 'format', 'full_clean',
'id', 'object', 'object_id', 'object_id_int', 'object_repr',
'object_version', 'objects', 'pk', 'prepare_database_save', 'revert',
'revision', 'revision_id', 'save', 'save_base', 'serializable_value',
'serialized_data', 'unique_error_message', 'validate_unique']

Check the revision attribute of the Version object. 检查Version对象的revision属性。 Notice that the usual way to get a list of Version s for a specific object obj is to use the reversion.get_for_object(obj) method. 请注意,获取特定对象objVersion列表的通常方法是使用reversion.get_for_object(obj)方法。

Also, I've written a rather comprehensive Post about reversion (and other similar solutions) @ http://spapas.github.io/2015/01/21/django-model-auditing/ 另外,我在http://spapas.github.io/2015/01/21/django-model-auditing/上撰写了一篇有关还原(以及其他类似解决方案)的综合文章。

Create a function in your views as below 在您的视图中创建一个函数,如下所示

from reversion.models import Version
import json

def history_list(request)
 history_list = Version.objects.all().oreder_by('revision_date_created')
 data = []
 for i in history_list:
  data.append({
     'user': str(i.revision.user),
     'comment': i.revision.comment
  })
print(data)

Instead of printing in your terminal if you would like to have a route where it should print user and comment as json add the additional to above function 如果您希望在路线上打印用户并注释为json,那么可以在终端中打印而不是在json上添加其他功能

from django.http import HttpRespose
...............
...............
data_ser = json.dumps(data)
return HttpResponse(data_ser, content_type="application/json")

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

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