0

我有一个项目,其中一些用户可以执行 CRUD 活动。我想记录谁在什么时候做了什么。目前,我正在考虑制作模型

class UserAction(models.Model):
    user_id = models.CharField(max_length=100)
    action_flag = models.CharField(max_length=100)
    class_id = models.CharField(max_length=100)
    action_taken_at = models.DateTimeField(default=datetime.now())

并制作一个填充我的 UserAction 表的函数。有没有更好的方法来做到这一点?

4

2 回答 2

1

应用程序/模型.py:

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

class Action(models.Model):
    sender = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE)
    verb = models.CharField(max_length=255)
    target_ct = models.ForeignKey(ContentType, blank=True, null=True,
    related_name='target_obj', on_delete=models.CASCADE)
    target_id = models.PositiveIntegerField(null=True, blank=True)
    target = GenericForeignKey('target_ct', 'target_id')
    created = models.DateTimeField(auto_now_add=True)
    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.pk 

应用程序/admin.py

from .models import Action
admin.site.register(Action)

你怎么能用它?
您现在可以在您的任何views.py 中导入此模型(操作)。例如,如果您有一个帖子并且用户喜欢它。您可以只写

Action.objects.create(sender=request.user,verb="likes this post",target=post)

现在当您查看您的管理员时,您会看到 tartget_id=post.pk 在这里我假设用户已通过身份验证,您可以为自己更改它。快乐编码!

于 2021-09-27T07:17:06.327 回答
1

您可以通过在 Models.py

class Auditable(models.Model):
ip = models.GenericIPAddressField(null=True)
user_agent = models.CharField(max_length=255, blank=True)
remote_host = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="%(app_label)s_%(class)s_created_by", null=True, blank=True)  # this is for web user
modified_at = models.DateTimeField(auto_now=True, blank=True, null=True)
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="%(app_label)s_%(class)s_modified_by", null=True, blank=True)  # this is for web user

class Meta:
    abstract = True

def get_fields(self):
    list_fields = ['ip', 'user_agent',
                   'remote_host', 'created_by', 'modified_by']
    return [(field.verbose_name, field._get_val_from_obj(self)) for field in self.__class__._meta.fields if field.name not in list_fields and not
            (field.get_internal_type() == "DateTimeField" and
             (field.auto_now is True or field.auto_now_add is True)) and
            field.concrete and (not field.is_relation or field.one_to_one or
            (field.many_to_one and field.related_model))]

你可以给任何类名(我给了可审计的)。所以你所要做的就是在你的每个模型中传递这个类(可审计的)而不是 models.Model

例如: class Student(Auditable):

通过这样做,它将在您创建的每个表中添加所有可审计字段记录。希望您可以通过这样做得到答案。

于 2021-09-27T07:28:21.707 回答