Django Admin的save_model方法并不會(huì)立即保存模型到數(shù)據(jù)庫舌厨,而是只是創(chuàng)建了一個(gè)保存模型的數(shù)據(jù)庫事務(wù)。這個(gè)事務(wù)會(huì)在save_model方法執(zhí)行完畢后提交忿薇,也就是說邓线,在save_model方法中淌友,無論你把清除緩存的代碼放在哪里,都是在模型真正保存到數(shù)據(jù)庫之前執(zhí)行的骇陈。
- 直接清除緩存震庭,需要保存兩次,第一次實(shí)際數(shù)據(jù)未保存
from django.contrib import admin
from django.core.cache import caches
from myapp.models import YourModel
class YourModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
# 在這里清除緩存
caches['default'].delete(key)
admin.site.register(YourModel, YourModelAdmin)
- 使用transaction.on_commit來確保只有在事務(wù)成功提交后才執(zhí)行某個(gè)操作
from django.contrib import admin
from django.core.cache import caches
from myapp.models import YourModel
class YourModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
# 在這里清除緩存
transaction.on_commit(lambda: caches['default'].delete(key))
admin.site.register(YourModel, YourModelAdmin)