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的时候,表还未建好,你执行操作表的行为都将报错。

猜你喜欢

转载自www.cnblogs.com/dongqiSilent/p/10896798.html