如何获取修改对象的用户? django-简单历史

How to get the user that modified an object? django-simple-history

我正在尝试使用 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()

然后在 Shell 我做:

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

谢谢,

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

customer.history.all().last()<strong>.history_user</strong>

请注意,您只能通过网络服务器中的用户进行更改,例如通过视图或 ModelAdmin。如果你用 Django shell 本身进行更改,则没有“active 用户”,那么历史记录中存储的用户将是 NULL /None.