问题描述
我一年前部署了一个应用程序。在生产中,我不愿意手动更改所有模型以添加created_by
和modified_by
字段,因为这样做风险很小。
无论如何,我们可以用更少的代码来解决它(我们至少可以在将来的交易中将这些字段添加到每个模型中)来实现它
我当时想用猴子修补它,但不知道如何实现?
from django.apps import apps
from django.db import models
from django.contrib.auth import get_user_model
model_list = apps.get_models()
#-- Monkey Patch
for model in model_list:
if model != get_user_model():
model.add_to_class('created_by',models.CharField(max_length=250,blank=True,null=True))
model.add_to_class('modified_by',null=True))
def save(self):
if self.pk:
self.created_by = request.user.id #not sure,how I would get the user here from request
self.modified_by = request.user.id
return super(model,self).save(*args,**kwargs)
model.add_to_class("save",save)
解决方法
您可以考虑使用包含这些字段的基本抽象模型,并从中继承您的其他模型。不确定如何在迁移中使用。
,我认为最好的方法是使用这两个字段创建一个抽象类,并在每个类中从中继承。唯一要记住的是,您将需要为它们提供一个初始值:
class UserAction(models.Model):
created_by = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True,null=True)
modified_by = models.ForeignKey(User,null=True)
class Meta:
abstract = True
# Inherit from UserAction class
class MyClasses(UserAction):
# ... fields