Django 想要单独执行文件
Django 单独文件执行 文件
我是在项目根目录文件创建的。
配置文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django_login_publishing.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
你要执行的文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django_login_publishing.settings") # 在Django 里想单独执行文件写上这句话 import django # 导入Django django.setup() # 执行 from app01 import models # models.Press.objects.create(name="光辉出版社") # ret=[] # for i in range(300): # obj=models.Press(name="光辉第{}出版社".format(i))django_content_type # ret.append(obj) # models.Press.objects.create(ret) ret = [models.Press(name="火星第{}出版社".format(i)) for i in range(300)] # 批量创建300个出版社对象 models.Press.objects.bulk_create(ret) # 只向数据库提交一次
你就可以这样执行了: