简体   繁体   中英

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

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 :)

For Django 1.9, I only needed a couple of files from what you get after running django-admin startproject : settings.py with just 3 variables, and manage.py. Those two, plus a snippet of code from wsgi.py , and some basic directory structure elements get you a working standalone ORM setup. And really, if you don't want to do migrations, you could strip out manage.py.

Here's how you do it, and the link to GitHub to play for yourself.

Project Structure:

├── data
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   └── models.py
├── main.py
├── manage.py
└── settings.py

The data directory and migrations directory contain empty __init__.py files. The sample models.py file reads as follows:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)

The manage.py file is the typical Django manage.py file. Just be sure to change the settings param in os.environ.setdefault if you copy it from a fresh django-admin startproject command:

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

The settings.py file requires 3 settings: DATABASES, INSTALLED_APPS, and SECRET_KEY. Refer to Django docs for DBs that aren't SQLite:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'sqlite.db',
    }
}

INSTALLED_APPS = (
    'data',
    )

SECRET_KEY = 'REPLACE_ME'

The real trick is in main.py , which will be where you can code against your models. Apparently you have to use some code from wsgi.py to get things working with these two lines:

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Here's a sample main.py:

# Django specific settings
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

### Have to do this for it to work in 1.9.x!
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
#############

# Your application specific imports
from data.models import *

#Add user
user = User(name="someone", email="someone@example.com")
user.save()

# Application logic
first_user = User.objects.all()[0]

print(first_user.name)
print(first_user.email)

This project along with this post were helpful starting points for me to find the answer, and my pull request with working code for Django 1.9 was merged, so you can grab the code from masnun's repo now. If you know of a better way, please submit a pull request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM