Use Django ORM outside of Django

后端 未结 2 853
不思量自难忘°
不思量自难忘° 2020-12-31 20:53

I\'m new to Django and want to use its ORM in my scripts without running whole Django thing. I\'m scratching my head how to configure it. Searches on StackOverflow didn\'t h

相关标签:
2条回答
  • 2020-12-31 21:47

    Here's an updated version, fix was including django.setup() line and some additional settings and includes:

    manage.py

    import os
    import sys
    import django
    from django.conf import settings
    
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    
    INSTALLED_APPS = [
        'orm',
    ]
    
    DATABASES = {
        'default': {
            'ENGINE' : 'django.db.backends.mysql',
            'NAME' : 'playground',
            'USER' : 'admin',
            'PASSWORD' : 'pasw',
            'HOST' : 'localhost',
        }
    }
    
    settings.configure(
        INSTALLED_APPS = INSTALLED_APPS,
        DATABASES = DATABASES,
    )
    
    django.setup()
    
    if __name__ == "__main__":
        from django.core.management import execute_from_command_line
    
        execute_from_command_line(sys.argv)
    

    And app.py:

    import manage
    from orm.models import Label
    
    if __name__ == '__main__':
    
        Label.objects.create(name='test')
        print(Label.objects.get(name='test'))
    

    Hope someone will find it useful.

    0 讨论(0)
  • 2020-12-31 21:55

    So your question is :

    I want to use Django's ORM in my scripts without running a complete Django application, how to configure it?

    I'll share what I did for a project I am currently working on, using Django 2.0.2.

    I suggest you create a file SetupDjangoORM.pywith :

    import django
    from django.conf import settings
    
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': '<your_engine>',
                'NAME': '<database_name>',
                'HOST': '<hostname_or_ip>',
                'PORT': '<port>',
                'USER': '<user>',
                'PASSWORD': '<super_secret_password>',   
            }
        },
        INSTALLED_APPS=[
            '<your_app>',
        ]
    )
    django.setup()
    

    You can find this informations in your settings.py file.

    Then, you can import this wherever you need :

    from . import SetupDjangoORM
    

    And now you are able to use Django Models (ORM) in your scripts.

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