Use Django ORM outside of Django

后端 未结 2 869
不思量自难忘°
不思量自难忘° 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: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': '',
                'NAME': '',
                'HOST': '',
                'PORT': '',
                'USER': '',
                'PASSWORD': '',   
            }
        },
        INSTALLED_APPS=[
            '',
        ]
    )
    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.

提交回复
热议问题