當前位置:首頁 » 操作系統 » django創建資料庫

django創建資料庫

發布時間: 2022-04-23 04:39:14

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)

  • 執行數據遷移命令:
  • [python]view plain

  • pythonmanage.pymakemigration

  • pythonmanage.pymigrate

  • 會在資料庫中生成名稱為show_sciencenews的數據表。show為應用名稱,此處我的應用名稱為show。可以看到Django創建表的命名規則:應用名_模型名。
  • 我的存儲爬取到的數據的表格名稱原來為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

熱點內容
mac訪問windows共享 發布:2024-10-01 23:31:58 瀏覽:643
java培訓要學什麼 發布:2024-10-01 23:15:54 瀏覽:539
c語言編程學習寶典 發布:2024-10-01 22:35:08 瀏覽:346
無法打開腳本文件 發布:2024-10-01 22:14:51 瀏覽:110
javaxml格式字元串格式 發布:2024-10-01 21:54:03 瀏覽:657
為什麼安卓玩游戲都選驍龍 發布:2024-10-01 21:48:07 瀏覽:377
如何避免伺服器暴露ip 發布:2024-10-01 21:38:24 瀏覽:221
pythonrequestjson 發布:2024-10-01 21:37:37 瀏覽:858
珠海java 發布:2024-10-01 21:07:29 瀏覽:825
伺服器剩餘維護是什麼 發布:2024-10-01 21:03:46 瀏覽:547