For Django model manipulation and references,
python manage.py MY_COMMAND
You can do it, but you have to put it under the Django application as /app_name/management/commands/MY_COMMAND.py
, inheritBaseCommand
and do as follows.
MY_COMMAND.py
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **options):
print 'hogefuga'
By doing this, the above manage.py MY_COMMAND
can be used as an extension command for Django.
The above is fine if you want to create something related to the Django app.
If you have a Django DB as the master of some management information, or if you want to use the stored results to link with a completely different program, you want to call it from the outside instead of extending manage.py
. ..
Since the back of Django is just SQLite or MySQL, you can access it directly and read the information, but even though you defined Model in Django, you do not use that ORM. So, it's a way to use ORM from the outside.
You can also use Django's ORM from outside by following the steps below.
--Specify a Django project in sys.path
--Specify project settings.py
in Django's environment variable DJANGO_SETTINGS_MODULE
--import of models
ORM_test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
def CallORMapper():
sys.path.append('/YOUR/DJANGO-PROJECT')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DJANGO-PROJECT.settings")
objects = MODEL_NAME.objects.all()
from DJANGOAPPNAME.models import MODEL_NAME
print objects
if __name__ == "__main__":
CallORMapper()
-Use the Django model from outside the Django project
Recommended Posts