John Kaff John Kaff - 6 months ago 25
Python Question

What minimal files i need to use django ORM

I have python module for doing some stuff and i need to save few items in database.

Currenlt i am using raw sql to insert data. But i want to use django ORM for that.

I don't need any urls , views etc. all i want is that i can create models and then should be able to save it like

user.save()


Now i don't want to have unnecessary files and data in there . but i am not sure which files i need to have. Do i need

settings.py
urls.py
views.py
app folder.


Is it possible to have just
models.py
and then in settings the
DATABASE config
.

DO i need to create an app as well

Answer

You'll need settings.py. You will not need urls.py or views.py. You will need an app folder, and to have that app under INSTALLED_APPS in settings.py. While there is a way of discovering apps manually, it might be more work than you're hoping to get into.

You'll also need to run migrations, and in doing so make a migration directory and files.

Inside of the app directory, all you really need is the __init__.py file, the migrations directory, and the models.py file

In models.py, have "from django.db import models" and then have your models inherit from models.Model.

Get all that going, and you've got a pretty barebones Django setup for using your models to interact with a database

EDIT

To play around with this, I started a new Django 1.9 project and began butchering the settings.py file until I broke something. This is what I started with:

"""
Django settings for Test project.

Generated by 'django-admin startproject' using Django 1.9.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'yp0at6d_bpr5a^j$6$#)(17tj8m5-^$p773lc6*jy%la!wu5!i'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'modeltest',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Test.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Test.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

I also made a sample github repo so you can explore what a minimal setup might look like. https://github.com/RobertTownley/BarebonesDjango

Things I was able to do without breaking DB interactions (as long as I did this all at once, and before migrations were run for the first time):

  1. Remove admin, views and tests from my "modeltest" app
  2. Remove wsgi.py (assuming this will never see production, nor will it ever be used to actually run a web server)
  3. Remove literally everything from urls.py and leave it as a blank file (unfortunately, settings.py expects ROOT_URLCONF to point at something)
  4. Remove all MIDDLEWARE_CLASSES from settings.py, along with TEMPLATES, WSGI_APPLICATION, all internationalization features, DEBUG, ALLOWED_HOSTS, and all comments :)

So at the end of this experiment, I can interact with my barebones model (including adding new fields) with a settings.py file that looks like this:

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'v7j%&)-4$(p&tn1izbm0&#owgxu@w#%!*xn&f^^)+o98jxprbe'
INSTALLED_APPS = ['modeltest']
ROOT_URLCONF = 'BarebonesTest.urls'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

If I knew the exact filepath of the desired location of the sqlitedb, or switched to postgres/mysql, I could get rid of that import statement and the BASE_DIR, bringing my settings.py line total down to 4 substantive lines (the db setting, root_url, installed_apps and secret_key)

I'd love to be proven wrong (learning is fun), but I don't think you'll be able to get down to a smaller settings.py file than that :)