ARTS打卡计划第5周-TIPS

使用django开发web 的时候,经常需要在系统第一次初始化的时候,添加一些类似字典的初始化数据,这些数据存在数据库之中。我分享一种,在初始化的时候,自动执行一些向数据库添加记录的操作。

在我们的项目的某一个app的目录下,在apps.py中添加类似代码

class ErpConfigConfig(AppConfig):
    name = 'erp_config'

    def ready(self):
        post_migrate.connect(import_sql, self, )
        print('erp_config 初始化成功')

  然后我们需要定义一个import_sql方法,该方法进行一些初始化数据的操作。这里我使用的是导入2个sql文件,其实你也可以定义一些model的save的操作。

def is_data_empty():
    from .models import DictType, DictValue
    count_dict_type = DictType.objects.count()
    if count_dict_type:
        logging.error("erp_config_dict_type表 已经有数据,无法导入")

    count_dict_value = DictValue.objects.count()
    if count_dict_value:
        logging.error("erp_config_dict_value表 已经有数据,无法导入")

    if count_dict_type or count_dict_value:
        return False
    return True


def import_sql(sender, **kwargs):
    if is_data_empty():
        load_data_from_sql('erp_config_dict_type.sql')
        load_data_from_sql('erp_config_dict_value.sql')


def load_data_from_sql(filename):
    file_path = os.path.join(os.path.dirname(__file__), 'sql', filename)
    sql_statement = open(file_path).read()
    with connection.cursor() as cursor:
        cursor.execute(sql_statement)

  这里需要注意的是,必须使用post_migrate而不是直接执行import_sql,因为在你migrate的时候,表还未建好,你执行操作表的行为都将报错。

转载于:https://www.cnblogs.com/dongqiSilent/p/10896798.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值