Django: How can I use my model classes to interact with my database from outside Django?

后端 未结 3 703
囚心锁ツ
囚心锁ツ 2020-12-23 18:29

I\'d like to write a script that interacts with my DB using a Django app\'s model. However, I would like to be able to run this script from the command line or via cron. W

3条回答
  •  死守一世寂寞
    2020-12-23 18:48

    You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):

    import os
    
    os.environ['PYTHONPATH'] = '/path/to/myproject'
    os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
    

    Now you should be able to access the models:

    from myproject.models import MyModel
    
    all_my_models = MyModel.objects.all()
    

提交回复
热议问题