[英]What is the best approach to automatocally save who created or modified a row in the database?
我的目標是建立一個具有以下屬性的抽象BaseModel模型:
對於date_created和date_updated,可以,我可以使用auto_now
和auto_now_add
參數。
對於created_by和updated_by,我找不到如何以線程安全的方式自動執行此操作。 當然,我可以對視圖上的每個模型執行此操作,但是我想避免重復自己並一次在一個位置執行此操作。
所以我想像在我的抽象模型上訪問會話請求或請求對象一樣...
任何想法?
您無權訪問模型中的請求(因此也無法訪問當前用戶)。 這是在Django中設計的。
更直接的方法是更少的DRY,但更明確:
ModelForm
,在保存表單時自動將用戶保存到模型 View
,該View
可自動將用戶保存到模型中 ModelAdmin
自動將用戶保存到模型 (或此答案 ) 但是,如果您想要真正透明地保存創建者/修改者,那就是更干燥,但不太明確,您可以:
save()
方法中再次訪問該threadlocal。 您需要小心使用threadlocals 這是更透明的選項中的第一個:
from django.db.models import signals
from django.utils.functional import curry
class WhodidMiddleware(object):
def process_request(self, request):
if not request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
if hasattr(request, 'user') and request.user.is_authenticated():
user = request.user
else:
user = None
mark_whodid = curry(self.mark_whodid, user)
signals.pre_save.connect(mark_whodid, dispatch_uid = (self.__class__, request,), weak = False)
def process_response(self, request, response):
signals.pre_save.disconnect(dispatch_uid = (self.__class__, request,))
return response
def mark_whodid(self, user, sender, instance, **kwargs):
if 'created_by' in instance._meta.fields and not instance.created_by:
instance.created_by = user
if 'modified_by' in instance._meta.fields:
instance.modified_by = user
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.