存储谁从管理员更新了 Django 模型

Store who updated Django Model from admin

我有一个用例,其中仅从 django admin 插入和更新数据。现在,我有多个用户可以访问 django 管理页面。我希望能够存储谁在 Django 管理页面中准确地更新或创建了记录。

理想情况下,我想向现有模型添加一个单独的列。

models.py

class Links(models.Model):
    link = models.URLField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = model.ForeignKey(UserModel)
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = model.ForeignKey(UserModel)

您可以覆盖 .save_model(…) method [Django-doc] 以设置 .updated_by.created_by 字段,具体取决于 changeTrue 还是 False :

from django.contrib import admin

class LinkAdmin(admin.ModelAdmin):
    
    def <strong>save_model</strong>(self, request, obj, form, change):
        if not change:
            obj<strong>.created_by</strong> = request.user
        obj<strong>.updated_by</strong> = request.user
        return super().save_model(request, obj, form, change)

admin.site.register(Links, LinkAdmin)

如果你需要它用于大量模型,你可以制作一个 mixin,然后将其用于各种模型:

class <strong>CreateUpdateUserAdminMixin</strong>:
    
    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        obj.updated_by = request.user
        return super().save_model(request, obj, form, change)

然后使用mixin:

class LinkAdmin(<strong>CreateUpdateUserAdminMixin</strong>, admin.ModelAdmin):
    pass

class OtherModelAdmin(<strong>CreateUpdateUserAdminMixin</strong>, admin.ModelAdmin):
    pass

admin.site.register(Links, LinkAdmin)
admin.site.register(OtherModel, OtherModelAdmin)

Note: normally a Django model is given a singular name, so Link instead of Links.