zoukankan      html  css  js  c++  java
  • 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的时候,表还未建好,你执行操作表的行为都将报错。

  • 相关阅读:
    4、提取看似无用的委托变量,减少构造开销
    Cloud Foundry buildpack
    mysql中engine=innodb和engine=myisam的区别
    Maven中dependencyManagement的作用
    bean
    servlet
    web服务器 应用服务器区别 web框架
    Java和Python的Web开发
    spring mvc controller 高并发问题
    es 批量添加数据
  • 原文地址:https://www.cnblogs.com/dongqiSilent/p/10896798.html
Copyright © 2011-2022 走看看