2

我正在尝试使用 django-simply-history 库保存对象的历史记录,到目前为止,我可以看到对象本身的更改,但看不到进行更改的用户。

我有以下设置。

设置:

# settings.py

INSTALLED_APPS = [
    # ...
    'simple_history',
    # ...
]

MIDDLEWARE = [
    # ...
    'simple_history.middleware.HistoryRequestMiddleware',
    # ...
]

楷模:

from django.db import models

from apps.companies.models import Company
from simple_history.models import HistoricalRecords

# Create your models here.
class Customer(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=20)
    dateCreated = models.DateTimeField(auto_now_add=True,)
    dateUpdated = models.DateTimeField(auto_now=True,)
    telephone = models.CharField(max_length=20, blank=True, null=True)
    address = models.CharField(max_length=20, blank=True, null=True)
    email = models.EmailField(max_length=254, blank=True, null=True)

    history = HistoricalRecords()

然后在壳牌我做:

customer = Customer.objects.all().last()

customer.name = "Test"

customer.save()

customer.history.all().last()

Out[79]: <HistoricalCustomer: Customer object (d2211cc1-9762-4f6d-9086-634deee95b1e) as of 2021-08-24 09:28:44.978543+00:00>

# How can I print the user that changed the object????
customer.history.all().last()_history_user

谢谢,

4

1 回答 1

2

.history_user简单的历史中间件将在历史记录的字段中存储进行更改的用户。因此,您可以获得更改Customer对象的最新用户:

customer.history.all().last().history_user

请注意,您只能与网络服务器中的用户进行更改,例如使用视图或使用ModelAdmin. 如果您使用 Django shell 本身进行更改,则没有“活动用户”,在这种情况下,存储在历史记录中的用户将是NULL/ None

于 2021-08-24T10:40:56.830 回答