83π
You just need to configure the Django settings before you do any calls, including importing your models. Something like this:
from django.conf import settings
settings.configure(
DATABASE_ENGINE = 'postgresql_psycopg2',
DATABASE_NAME = 'db_name',
DATABASE_USER = 'db_user',
DATABASE_PASSWORD = 'db_pass',
DATABASE_HOST = 'localhost',
DATABASE_PORT = '5432',
TIME_ZONE = 'America/New_York',
)
Again, be sure to run that code before running, e.g.:
from your_app.models import *
Then just use the DB API as usual.
19π
For django 1.7, I used the following to get up and running.
settings.py:
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name',
'USER': 'usr',
'PASSWORD': 'secret',
'HOST': '127.0.0.1',
'PORT': '5432',
},
},
TIME_ZONE='America/Montreal',
)
In the file containing the startup routine
import os
import django
import v10consolidator.settings
from myapp.models import *
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
"myapp.settings"
)
django.setup()
- [Django]-How to set current user to user field in Django Rest Framework?
- [Django]-Django multiprocessing and database connections
- [Django]-How do you know if memcached is doing anything?
11π
Update setup_environ is to be removed in django 1.6
If youβre able to import your settings.py file, then take a look at handy setup_environ command.
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
#here you can do everything you could in your project
- [Django]-Unique fields that allow nulls in Django
- [Django]-How to simplify migrations in Django 1.7?
- [Django]-Passing STATIC_URL to file javascript with django
11π
I was looking for answers for django 3.0 and none of the above method exactly worked for me.
I read the official docs at https://docs.djangoproject.com/en/3.0/topics/settings/ and this scripts worked for me.
Project Structure
mysite
mysite
...
settings.py
db.sqlite3
db_tasks.py
manage.py
polls
db_tasks.py:
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()
from polls.models import Question
print(Question.objects.all())
out: <QuerySet [<Question: WTU?]>
- [Django]-How to recursively query in django efficiently?
- [Django]-How to add data into ManyToMany field?
- [Django]-Error when using django.template
- [Django]-Django admin and MongoDB, possible at all?
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- [Django]-Testing email sending in Django
9π
Here is the code I use. Just replace your_project
with your Django project name, yourApp
with your Django app name, any_model
with the model you want to use in models file and any_fild
with the field you want to get from the database:
from django.conf import settings
import django
from your_project.settings import DATABASES, INSTALLED_APPS
settings.configure(DATABASES=DATABASES, INSTALLED_APPS=INSTALLED_APPS)
django.setup()
from yourApp.models import *
print(any_model.objects.all()[0].any_fild)
- [Django]-What is the difference between cached_property in Django vs. Python's functools?
- [Django]-"Failed building wheel for psycopg2" β MacOSX using virtualenv and pip
- [Django]-How can I filter a Django query with a list of values?
3π
For using Django ORM from other applications you need:
1) export DJANGO_SETTINGS_MODULE=dproj.settings
2) Add your Django app folder to the path (you can do it in the code of your non-django-app):
sys.path = sys.path + ['/path/to/your/app/']
3) If using SQLite, use the full path to the db file in settings.py:
DATABASE_NAME = '/path/to/your/app/base.db'
- [Django]-Django: import auth user to the model
- [Django]-Django-allauth social account connect to existing account on login
- [Django]-Django.db.migrations.exceptions.InconsistentMigrationHistory
3π
For django 1.5 on (multiple databases are supported) the DATABASE settings also changed.
You need to adapt the previous answer to β¦
settings.configure(
DATABASES = { 'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name',
'USER': 'db_usr',
'PASSWORD': 'db_pass',
'HOST': '',
'PORT': '',
}, },
TIME_ZONE = 'Europe/Luxembourg'
)
- [Django]-Django: Calculate the Sum of the column values through query
- [Django]-Celery discover tasks in files with other filenames
- [Django]-How can I filter a Django query with a list of values?
3π
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
from app.models import MyModel
- [Django]-When to use get, get_queryset, get_context_data in Django?
- [Django]-How to update an existing Conda environment with a .yml file
- [Django]-What is a "django backend"?
2π
Based on the answer by Hai Hu, here is a working script, tested on Django 1.10 and 1.11.
I first import Djangoβs base apps because they are needed in many other apps.
import os
from django.conf import settings
from django.apps import apps
conf = {
'INSTALLED_APPS': [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sitemaps',
'django.contrib.sites',
'django.contrib.staticfiles',
'<your_app>',
],
'DATABASES': {
'default': {
'ENGINE': os.environ.get('DB_ENGINE'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
}
},
'TIME_ZONE': 'UTC'
}
settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)
<import your app models here>
- [Django]-Django simple_tag and setting context variables
- [Django]-Django: using more than one database with inspectdb?
- [Django]-Form field description in django admin
1π
In Django >= V.3.2.3
Put the following before you model import
import os
import django
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'mymodule.settings'
)
django.setup()
from app.models import MyModel
Then use your model as usual.
myitem = MyModel()
myitem.data = 'some data'
myitem.save()
Regards
- [Django]-How to get the name of current app within a template?
- [Django]-How to add custom field in ModelSerializer?
- [Django]-How to access outermost forloop.counter with nested for loops in Django templates?
0π
for django 3+ :
#########################
directory and files structure:
βmy_project
β-my_project > settings.py
β-myapps
##########################
import sys
sys.path.append("C:/Users/khder/Desktop/test/my_project") #append your main project directory path
import os
import django
#define your setting file as the following.
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'my_project.settings'
)
django.setup()
from my_app.models import MyModel
qs = MyModel.objects.all()
print(qs)
note: for path always use slash β/β not backslash β even if you are using windows.
this is just example and change it based on your case/requirement.
i hope this helpful .
done.
- [Django]-Check if key exists in a Python dict in Jinja2 templates
- [Django]-Django delete FileField
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'