django创建数据库
A. django orm创建数据表
Django里面,管理数据库和sqlarchemy类似,也是通过orm框架来实现的。所有的数据库的建立,都是在model.py里面通过类来实现的。
首先看看如何创建一个单表:
a. 先定义一个类,继承models.Model, 然后根据需求定义参数,这些参数的类型和变量后面会进一步阐述
models.py
fromdjango.dbimportmodels
classUserInfo(models.Model):
username=models.CharField(max_length=32)
password=models.CharField(max_length=64)
b. 注册app
settings.py
INSTALLED_APPS=[
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app01‘,
]
c.执行命令。 第一条命令会生成一个初始化文件,第二个命令会生成对应的表
pythonmanage.pymakemigrations
pythonmanage.pymigrate
2. 对于单表的增删改查询
查询
获取所有结果,获取到的结果是一个QuerySet的类似列表的对象,每一个元素本身又是一个对象,包括了id,name,password等属性。
obj=models.UserInfo.objects.all()
<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
可以通过filter进行过滤,相当于sql的where语句,因为结果也是QuerySet,因此需要再使用first()获取第一个值
obj=models.UserInfo.objects.filter(id=nid).first()
增加
models.UserInfo.objects.create(username=u,password=p,user_group_id=3)
删除,可以在filter的基础上进行删除
models.UserInfo.objects.filter(id=nid).delete()
修改,有两种常见方式
第一个方式
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
第二个方式
obj=models.UserInfo.objects.filter(id=nid)
obj.username=u
obj.save()
B. django使用已有的数据库表怎么建立model
在网上看到都是使用Django的models和makemigration,migrate命令来创建新表,并使用。可是我的数据已经存在了已经创建好,并且已经存储有数据了,不能再重新创建新表了。了解Django的表明和models名称的映射关系就可以让Django使用已经存在的表。
假如在Django存在models如下:
[python]view plain
fromdjango.dbimportmodels
#Createyourmodelshere.
classSciencenews(models.Model):
id=models.CharField(max_length=36,primary_key=True)
first_mole=models.CharField(max_length=30,default="News")
second_mole=models.CharField(max_length=30,default="LatestNews")
title=models.CharField(max_length=300)
author=models.CharField(max_length=60,null=True)
publish_date=models.CharField(max_length=35,null=True)
content=models.TextField(null=True)
crawl_date=models.CharField(max_length=35,null=True)
from_url=models.CharField(max_length=350,null=True)
- 执行数据迁移命令:
pythonmanage.pymakemigration
pythonmanage.pymigrate
- 会在数据库中生成名称为show_sciencenews的数据表。show为应用名称,此处我的应用名称为show。可以看到Django创建表的命名规则:应用名_模型名。
[python]view plain
我的存储爬取到的数据的表格名称原来为science_news,想要Django使用它,而不是创建新的表,只需要把的它的名称改为:应用名_要与该表映射的models名称,在此处我改为show_sciencenews。然后使用如上的数据迁移命令,这时可能会提示数据表已经存在的错误,不用理会,models已经和数据表映射上了。接下来只需要正常使用models和数据表就可以了。
C. python3.6下如何用Django1.9创建数据库报错
错误描述
python==3.5
django==1.7
django创建项目时报错如下:
Traceback (most recent call last):
File "/root/envs/django-test/bin/django-admin", line 11, in <mole>
sys.exit(execute_from_command_line())
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/root/envs/django-test/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
from django.utils.log import configure_logging
File "/root/envs/django-test/lib/python3.5/site-packages/django/utils/log.py", line 10, in <mole>
from django.views.debug import ExceptionReporter, get_exception_reporter_filter
File "/root/envs/django-test/lib/python3.5/site-packages/django/views/debug.py", line 10, in <mole>
from django.http import (HttpResponse, HttpResponseServerError,
File "/root/envs/django-test/lib/python3.5/site-packages/django/http/__init__.py", line 4, in <mole>
from django.http.response import (HttpResponse, StreamingHttpResponse,
File "/root/envs/django-test/lib/python3.5/site-packages/django/http/response.py", line 13, in <mole>
from django.core.serializers.json import DjangoJSONEncoder
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 23, in <mole>
from django.core.serializers.base import SerializerDoesNotExist
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/serializers/base.py", line 6, in <mole>
from django.db import models
File "/root/envs/django-test/lib/python3.5/site-packages/django/db/models/__init__.py", line 6, in <mole>
from django.db.models.query import Q, QuerySet, Prefetch # NOQA
File "/root/envs/django-test/lib/python3.5/site-packages/django/db/models/query.py", line 13, in <mole>
from django.db.models.fields import AutoField, Empty
File "/root/envs/django-test/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 18, in <mole>
from django import forms
File "/root/envs/django-test/lib/python3.5/site-packages/django/forms/__init__.py", line 6, in <mole>
from django.forms.fields import * # NOQA
File "/root/envs/django-test/lib/python3.5/site-packages/django/forms/fields.py", line 18, in <mole>
from django.forms.utils import from_current_timezone, to_current_timezone
File "/root/envs/django-test/lib/python3.5/site-packages/django/forms/utils.py", line 15, in <mole>
from django.utils.html import format_html, format_html_join, escape
File "/root/envs/django-test/lib/python3.5/site-packages/django/utils/html.py", line 16, in <mole>
from .html_parser import HTMLParser, HTMLParseError
File "/root/envs/django-test/lib/python3.5/site-packages/django/utils/html_parser.py", line 12, in <mole>
HTMLParseError = _html_parser.HTMLParseError
AttributeError: mole 'html.parser' has no attribute 'HTMLParseError'
(django-test) root@localhost:~/source/djangotest# django-admin startproject superlists
Traceback (most recent call last):
File "/root/envs/django-test/bin/django-admin", line 11, in <mole>
sys.exit(execute_from_command_line())
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/root/envs/django-test/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
from django.utils.log import configure_logging
File "/root/envs/django-test/lib/python3.5/site-packages/django/utils/log.py", line 10, in <mole>
from django.views.debug import ExceptionReporter, get_exception_reporter_filter
File "/root/envs/django-test/lib/python3.5/site-packages/django/views/debug.py", line 10, in <mole>
from django.http import (HttpResponse, HttpResponseServerError,
File "/root/envs/django-test/lib/python3.5/site-packages/django/http/__init__.py", line 4, in <mole>
from django.http.response import (HttpResponse, StreamingHttpResponse,
File "/root/envs/django-test/lib/python3.5/site-packages/django/http/response.py", line 13, in <mole>
from django.core.serializers.json import DjangoJSONEncoder
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 23, in <mole>
from django.core.serializers.base import SerializerDoesNotExist
File "/root/envs/django-test/lib/python3.5/site-packages/django/core/serializers/base.py", line 6, in <mole>
from django.db import models
File "/root/envs/django-test/lib/python3.5/site-packages/django/db/models/__init__.py", line 6, in <mole>
from django.db.models.query import Q, QuerySet, Prefetch # NOQA
File "/root/envs/django-test/lib/python3.5/site-packages/django/db/models/query.py", line 13, in <mole>
from django.db.models.fields import AutoField, Empty
File "/root/envs/django-test/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 18, in <mole>
from django import forms
File "/root/envs/django-test/lib/python3.5/site-packages/django/forms/__init__.py", line 6, in <mole>
from django.forms.fields import * # NOQA
File "/root/envs/django-test/lib/python3.5/site-packages/django/forms/fields.py", line 18, in <mole>
from django.forms.utils import from_current_timezone, to_current_timezone
File "/root/envs/django-test/lib/python3.5/site-packages/django/forms/utils.py", line 15, in <mole>
from django.utils.html import format_html, format_html_join, escape
File "/root/envs/django-test/lib/python3.5/site-packages/django/utils/html.py", line 16, in <mole>
from .html_parser import HTMLParser, HTMLParseError
File "/root/envs/django-test/lib/python3.5/site-packages/django/utils/html_parser.py", line 12, in <mole>
HTMLParseError = _html_parser.HTMLParseError
AttributeError: mole 'html.parser' has no attribute 'HTMLParseError'5767757677
原因
HTMLParseError在pythons3.5已经没有了
解决方法
将python版本回退到3.3或3.4
升级django版本
D. django怎么创建mysql数据库
Model是django项目的基础, 如果一开始没有好好设计好, 那么在接下来的开发过程中就会遇到更多的问题. 然而, 大多数的开发人员都容易在缺少思考 的情况下随意的增加或修改model. 这样做的后果就是, 在接下来的开发过程中, 我们不得不做出更多努力...
E. django1.8更改了model后要怎样重建数据库
#如果你说用的是pycharm编译器的话:
使用ctrl+alt+r进入manage界面
然后输入makemigrations[appname]创建数据库引导文件
然后使用migrate[appname]来把model变化同步到数据库
#[appname]指你当前model所在的app,如果不指定appname;则编译全部app
#如果不是pycharm编译器的话,请再追问
F. django怎样自动创建数据库table
django创建数据库表方法如下:
catcher:mysitecatcher$pythonmanage.pymakemigrationsbooks
Migrationsfor'books':
0001_initial.py:
-CreatemodelAuthor
-CreatemodelBook
-CreatemodelPublisher
-Addfieldpublishertobook
catcher:mysitecatcher$pythonmanage.pysqlmigratebooks0001
BEGIN;
--
--CreatemodelAuthor
--
CREATETABLE"books_author"("id","first_name"varchar(30)NOTNULL,"last_name"varchar(40)NOTNULL,"email"varchar(254)NOTNULL);
--
--CreatemodelBook
--
CREATETABLE"books_book"("id","title"varchar(100)NOTNULL,"publication_date"dateNOTNULL);
CREATETABLE"books_book_authors"("id","book_id"integerNOTNULLREFERENCES"books_book"("id"),"author_id"integerNOTNULLREFERENCES"books_author"("id"));
--
--CreatemodelPublisher
--
CREATETABLE"books_publisher"("id","name"varchar(30)NOTNULL,"address"varchar(50)NOTNULL,"city"varchar(60)NOTNULL,"state_province"varchar(30)NOTNULL,"country"varchar(50)NOTNULL,"website"varchar(200)NOTNULL);
--
--Addfieldpublishertobook
--
ALTERTABLE"books_book"RENAMETO"books_book__old";
CREATETABLE"books_book"("id","title"varchar(100)NOTNULL,"publication_date"dateNOTNULL,"publisher_id"integerNOTNULLREFERENCES"books_publisher"("id"));
INSERTINTO"books_book"("publication_date","publisher_id","id","title")SELECT"publication_date",NULL,"id","title"FROM"books_book__old";
DROPTABLE"books_book__old";
CREATEINDEX"books_book_2604cbea"ON"books_book"("publisher_id");
COMMIT;
catcher:mysitecatcher$
catcher:mysitecatcher$sudopythonmanage.pymigratePassword:Operationstoperform:Applyallmigrations:admin,contenttypes,books,auth,sessionsRunningmigrations:Renderingmodelstates...DONEApplyingcontenttypes.0001_initial...OKApplyingauth.0001_initial...OKApplyingadmin.0001_initial...OKApplyingadmin.0002_logentry_remove_auto_add...OKApplyingcontenttypes.0002_remove_content_type_name...OKApplyingauth.0002_alter_permission_name_max_length...OKApplyingauth.0003_alter_user_email_max_length...OKApplyingauth.0004_alter_user_username_opts...OKApplyingauth.0005_alter_user_last_login_null...OKApplyingauth.0006_require_contenttypes_0002...OKApplyingauth.0007_alter_validators_add_error_messages...OKApplyingbooks.0001_initial...OKApplyingsessions.0001_initial...OKcatcher:mysitecatcher$
G. python django models创建mysql数据库表default、blank属性失效
default属性只在Django的ORM模型中有效,不会真正映射到数据库里。要设置数据表的DEFAULT属性,你可以手动修改makemigrations生成的脚本,或者去修改Django本身。
在db/backends/creation.py中找到如下字段:
iff.primary_key:
field_output.append(style.SQL_KEYWORD('PRIMARYKEY'))eliff.unique:
field_output.append(style.SQL_KEYWORD('UNIQUE'))
在之后加上:
if(f.default!=models.fields.NOT_PROVIDED):
field_output.append(style.SQL_KEYWORD('DEFAULT'+str(f.default)))
H. django怎么使用本机mysql数据库
step 1:
修改你的django project目录下的settings.py 文件至如下所示:
其中,'NAME' 对应的 ‘db_name' 是你事先使用mysql
的命令行提示符创建的数据库名称。注意:在django使用数据库之前,你必须先创建出数据库,否则会报错。'USER'对应的'username'
还有 'PASSWORD' 对应的‘passwd'
就是你在mysql中创建的用户名和密码。如果你有多个的话,随便填一个就好。'HOST'和'PORT'默认都可以不填。
题外话: 使用用户名和密码登录mysql的方法:
首先,你需要进入 mysql/bin的目录下,也可以在.bash_profile中设置环境变量:
PATH=/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/sbin:/usr/local/Cellar/mysql/5.6.22/bin/
再在prompt输入 mysql -u username -p, 回车后再输入 passwd即可
step 2:
然后,在manage.py路径中使用python manage.py syncdb 试试,结果会提示你错误找不到 MySQLdb 这个mole, 为什么呢, 因为 python manage.py syncdb 命令是这样工作的:
1. 在project目录的settings.py的INSTALLED_APPS元组中找到可能需要更新的APP。
2. 找到每一个APP目录中的models.py (关系定义文件),并针对变化在数据库中进行更新。
说了这么多,前面那个错误 找不到 mole MySQLdb 是什么意思啊 ?
先给个图,再解释:
因为在models.py中定义关系使用的是python,而真正在数据库中操作形成model当然一定要用sql语句,所以必须要有一些功能模块
来把python语句转化成sql语句。如果你使用sqlite的话,由于sqlite和转化模块都已经由python内置了,所以直接使用不会发生错
误。但是 ”mysql语句的转化模块“ 就需要你手动加载了,这些模块放在 MySQL-python 中。
我是使用pip 安装的:
安装了之后,再使用 python manage.py syncdb就OK啦。
我使用的系统是 OS X,下面是 mysql 默认的安装路径
/usr/local/Cellar/mysql/5.6.22/
如果你想知道你的数据库文件是放在哪里的,你可以查看mysql_config文件中的ldata变量,这个变量的值就是 默认的数据库文件夹存储的路径。 我的系统中,mysql_config的完整路径是 :
/usr/local/Cellar/mysql/5.6.22/bin/mysql_config