我需要使用django ORM的最小文件 [英] What minimal files i need to use django ORM

查看:128
本文介绍了我需要使用django ORM的最小文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有python模块做一些东西,我需要保存数据库中的几个项目。

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

Currenlt我正在使用raw sql插入数据。但是我想使用django ORM。

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.

有可能只有 models.py 然后在设置 DATABASE config

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

我需要创建一个应用程序

DO i need to create an app as well

推荐答案

你需要settings.py。您不需要urls.py或views.py。您将需要一个应用程序文件夹,并将该应用程序设置为settings.py中的INSTALLED_APPS。虽然有一种手动发现应用程序的方法,但它可能比您希望进入更多的工作。

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.

在应用程序目录中,您真正需要的是__init__.py文件,迁移目录和models.py文件

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

在models.py中,具有from django.db import models,然后将模型从models.Model继承。

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

获取所有这些,您有一个可靠的准系统Django设置,可以使用您的模型与数据库进行交互

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

EDIT

为了玩弄这个,我开始了一个新的Django 1.9项目,开始屠杀settings.py文件,直到我打破了一些东西这是我开始的:

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/'

我也做了一个样例github回购,所以你可以探索一个最小的设置可能是什么样子。 https://github.com/RobertTownley/BarebonesDjango

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. 从我的modeltest应用程序中删除管理员,查看和测试

  2. 删除wsgi.py(假设这将永远不会看到生产,也不会用于实际运行Web服务器)

  3. 从urls.py中删除所有内容,并将其保留为空白文件(不幸的是,settings.py希望ROOT_URLCONF指向某个东西)

  4. 从settings.py中删除所有MIDDLEWARE_CLASSES,连同TEMPLATES,WSGI_APPLICATION,所有国际化功能,DEBUG,ALLOWED_HOSTS和所有评论:)

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

所以在本实验结束时,我可以与我的准系统模型(包括添加新的字段)与一个settings.py文件进行交互如下所示:

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'),
    }
}

如果我知道sqlitedb的所需位置的确切文件路径,或者切换到postgres / mysql,我可以摆脱该导入语句和BASE_DIR,带来我的设置。 py线总共下降到4个实线(数据库设置,root_url,installed_apps和secret_key)

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)

我很乐意被证明是错误的(学习很有趣),但我不要以为你可以得到比这个更小的settings.py文件:)

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

这篇关于我需要使用django ORM的最小文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆