Accessing django models from a new script

后端 未结 3 2076
逝去的感伤
逝去的感伤 2021-02-11 09:42

I have seen many answers on how to use django models outside the project. But I have no success with any. I was trying to implement this answer but I get an error. I have create

相关标签:
3条回答
  • 2021-02-11 10:16

    As the exception says there are no apps installed ergo you have no models yet.

    from django.conf import settings
    settings.configure(
        DATABASE_ENGINE = 'sqlite3',
        DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
        # ....
        INSTALLED_APPS=["myapp","myotherapp"]
    
    )
    from myapp.models import *
    
    0 讨论(0)
  • 2021-02-11 10:26

    You need is importable settings.

    import os
    import django
    os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
    django.setup()
    from .models import 
    

    Another way call your script via the django shell:

    python manage.py shell < script.py
    
    0 讨论(0)
  • 2021-02-11 10:30

    The following solution work from a script located in the directory where your manage.py is located:

    import os
    from django.conf import settings
    from django.apps import apps
    
    conf = {
        'INSTALLED_APPS': [
            'Demo'
        ],
        'DATABASES': {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join('.', 'db.sqlite3'),
            }
        }
    }
    
    settings.configure(**conf)
    apps.populate(settings.INSTALLED_APPS)
    

    Replace Demo with your app name and put the correct database configuration for your app. This solution worked for me on Django 1.9.

    0 讨论(0)
提交回复
热议问题