如何在模型中保存当前用户而不为每个模型创建一个方法?有一种动态的方法可以在所有范围内实施此操作吗?像这样:
class BaseTable(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
modified_at = models.DateTimeField(auto_now=True, editable=False)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='%(class)s_createdby', editable=False)
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT ,related_name='%(class)s_modifiedby', editable=False)
class Meta:
abstract = True
然后我将新模型扩展到BaseTable
class Clients(BaseTable):
first_name = models.CharField(max_length=50,verbose_name='Nome')
last_name = models.CharField(max_length=50, verbose_name='Sobrenome')
我的问题:每当我需要覆盖所有模型中的save()
方法时:Clients, Invoices, Checkout
会将当前用户设置为ModelAdmin
还是有其他方法可以简化此过程?>
我正在使用:
admin.py
@admin.register(Clients)
class ClientsAdmin(admin.ModelAdmin):
model = Clients
def save_model(self, request, obj, form, change):
obj.created_by = request.user
obj.modified_by = request.user
super().save_model(request, obj, form, change)
有效。但是,如果一个有20个模型?我需要一一覆盖所有save_model方法吗?再没有动态了吗?
答案 0 :(得分:0)
解决问题:
一段时间后,我找到了解决方法:
1-调用前在 admin.py 中创建一个Mixin
class SetUserAdminMixin(object):
def save_model(self, request, obj, form, change):
obj.created_by_id = request.user.id
obj.modified_by_id = request.user.id
super(SetUserAdminMixin, self).save_model(request, obj, form, change)
2-在您的模型上将其称为继承,例如:
@admin.register(Clients)
class ClientsAdmin(SetUserAdminMixin, admin.ModelAdmin):
model = Clients
这会在调用时覆盖save_model()
方法。