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
原文地址:https://www.cnblogs.com/Xiaojiangzi/p/13093928.html