在Django之外使用Django ORM [英] Use Django ORM outside of Django

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

问题描述

我是Django的新手,并且想在我的脚本中使用其ORM,而无需运行整个Django.我正在摸索如何配置它. StackOverflow上的搜索无济于事,因为答案未显示完整内容.

I'm new to Django and want to use its ORM in my scripts without running whole Django thing. I'm scratching my head how to configure it. Searches on StackOverflow didn't help as answers don't show the full picture.

因此,我创建了一个小项目:

Therefore, I created a small project:

app.py
manage.py
orm/
  __init__.py
  models.py

manage.py具有配置:

manage.py has configuration:

from django.conf import settings    
settings.configure(
    DATABASE_ENGINE = 'mysql',
    DATABASE_NAME = 'db',
    DATABASE_USER = 'admin',
    DATABASE_PASSWORD = '',
    DATABASE_HOST = 'localhost',    
    INSTALLED_APPS = ('orm')
)

models.py:

models.py:

from django.db import models    
class Label(models.Model):
    name = models.CharField(max_length=50) # required max_length

最后是我的主文件app.py:

and finally my main file app.py:

from django.conf import settings    
from django.db import models
from orm.models import *   
\# do database maniupaltions

尽管在运行app.py之后,我收到一条错误消息: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Though after running app.py I receive an error that: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

我在做什么错了?

推荐答案

所以你的问题是:

我想在脚本中使用Django的ORM而不运行完整的Django应用程序,如何配置它?

I want to use Django's ORM in my scripts without running a complete Django application, how to configure it?

我将使用 Django 2.0.2 分享我当前正在做的项目的工作.

I'll share what I did for a project I am currently working on, using Django 2.0.2.

我建议您使用以下文件创建文件SetupDjangoORM.py:

I suggest you create a file SetupDjangoORM.pywith :

import django
from django.conf import settings

settings.configure(
    DATABASES={
        'default': {
            'ENGINE': '<your_engine>',
            'NAME': '<database_name>',
            'HOST': '<hostname_or_ip>',
            'PORT': '<port>',
            'USER': '<user>',
            'PASSWORD': '<super_secret_password>',   
        }
    },
    INSTALLED_APPS=[
        '<your_app>',
    ]
)
django.setup()

您可以在settings.py文件中找到此信息.

You can find this informations in your settings.py file.

然后,您可以将其导入到任何需要的地方:

Then, you can import this wherever you need :

from . import SetupDjangoORM

现在您可以在脚本中使用Django模型(ORM).

And now you are able to use Django Models (ORM) in your scripts.

这篇关于在Django之外使用Django ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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