django的save_model和delete_model修改admin后台修改數據時的行為


需求背景:

當在admin后台修改數據時,重新執行celery異步任務生成首頁靜態頁面

異步任務代碼如下:

@shared_task(name='celery_tasks.generate_static_index')
def generate_static_index():
    """生成首頁靜態頁面"""
    # 獲取商品分類信息
    goods_types = GoodsType.objects.all()
    # 獲取輪播圖信息
    goods_banners = IndexGoodsBanner.objects.all().order_by('index')  # 默認升序排列,如果降序則為"-index"
    # 獲取促銷活動信息
    promotion_banners = IndexPromotionBanner.objects.all().order_by('index')
    # 獲取首頁分類商品展示信息
    for type in goods_types:
        # 獲取type種類首頁展示的商品的圖片信息
        image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)
        # 獲取type種類首頁展示的商品的文字信息
        title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0)

        # 動態給type對象添加商品圖片、文字信息
        type.image_banners = image_banners
        type.title_banners = title_banners

    # 組織模板上下文信息
    context = {
        'goods_types': goods_types,
        'goods_banners': goods_banners,
        'promotion_banners': promotion_banners,

    }
    #生成靜態文件
    static_index_html = render_to_string('static_index.html',context=context)
    static_index_path = os.path.join(settings.BASE_DIR,'static/index.html')
    #將靜態文件存儲到static目錄下
    with open(static_index_path,'w',encoding='utf-8') as f:
        f.write(static_index_html)
View Code

admin中代碼如下:

from django.contrib import admin
from .models import GoodsType,IndexGoodsBanner,GoodsSKU,Goods,IndexPromotionBanner,IndexTypeGoodsBanner


class BaseModelAdmin1(admin.ModelAdmin):
    """"""
    def save_model(self, request, obj, form, change):
        """新增或者更新數據時調用"""
        super().save_model(request,obj,form,change)
        from celery_tasks.tasks import generate_static_index
        print('開始執行任務')
        generate_static_index.delay()

    def delete_model(self, request, obj):
        """刪除數據時調用"""
        super().delete_model(request,obj)
        from celery_tasks.tasks import generate_static_index
        generate_static_index.delay()

class IndexPromotionBannerAdmin(BaseModelAdmin1):
    pass

admin.site.register(IndexPromotionBanner,IndexPromotionBannerAdmin)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM