pythondjangoorm

How to use Django 1.8.5 ORM without creating a django project?


I've used Django ORM for one of my web-app and I'm very much comfortable with it. Now I've a new requirement which needs the database but nothing else that Django offers. I don't want to invest more time in learning another ORM like SQLAlchemy.

I think I can still do:

from django.db import models

and create models, but then without manage.py how would I do migration and syncing?


Solution

  • Django 1.11 documentation on how the applications are loaded

    For latest django version project structure would be-

    |--myproject
    |--main.py
    |--manage.py
    |--myapp
    |   |--models.py
    |   |--views.py
    |   |--admin.py
    |   |--apps.py
    |   |--__init__.py
    |   |--migrations
    |--myproject
    |   |--settings.py
    |   |--urls.py
    |   |--wsgi.py
    |   |--__init__.py
    

    You would still need manage.py to run migrations, main.py is your standalone script

    # main.py
    import os
    import django
    os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
    django.setup()
    from myapp.models import MyModel
    print(MyModel.objects.all()[0])