django迁移数据库在哪里(Django数据迁移)

网友投稿 471 2023-12-14

导读:很多朋友问到关于django迁移数据库在哪里的相关问题,本文首席CTO笔记就来为大家做个详细解答,供大家参考,希望对大家有所帮助!一起来看看吧!django迁移过后没有数据库django迁移过后没有数据库可以:

django迁移数据库在哪里(Django数据迁移)

修改数据库中相应表的字符集修改整个数据库的字符集修改mysql配置文件/etc/my.cnf.d/server.cnf,重启数据库django 跨数据库传输你说对了,假设你用数据库管理工具的话,你要先选择你工程所对应的数据库,比如mysql,直接用控制台操作的话,你需要先执行use。

yourdb,而用manage.pydbshell会自动链接到你用的数据库,省了输入用户名密码和useyourdb的过程。

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 这个module, 为什么呢, 因为 python manage.py syncdb 命令是这样工作的:

1. 在project目录的settings.py的INSTALLED_APPS元组中找到可能需要更新的APP2. 找到每一个APP目录中的models.py (关系定义文件),并针对变化在数据库中进行更新。

说了这么多,前面那个错误 找不到 module 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

如何解决Django 1.8在migrate时失败1. 创建项目运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :$ django-admin.py startproject mysite

创建后的项目目录如下:mysite├── manage.py└── mysite ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py

1 directory, 5 files说明:__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件 这是一个空文件,一般你不需要修改它manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。

键入python manage.py help,看一下它能做什么 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便settings.py :该 Django 项目的设置或配置urls.py:Django项目的URL路由设置。

目前,它是空的wsgi.py:WSGI web 应用服务器的配置文件更多细节,查看 How to deploy with WSGI接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONE。

SITE_ID = 1LANGUAGE_CODE = zh_CNTIME_ZONE = Asia/ShanghaiUSE_TZ = True 上面开启了 [Time zone]() 特性,需要安装 pytz:

$ sudo pip install pytz2. 运行项目在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:$ python manage.py migrateOperations to perform:

Apply all migrations: admin, contenttypes, auth, sessionsRunning migrations: Applying contenttypes.0001_initial... OK

Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying sessions.0001_initial... OK

然后启动服务:$ python manage.py runserver你会看到下面的输出:Performing system checks...System check identified no issues (0 silenced).

January 28, 2015 - 02:08:33Django version 1.7.1, using settings mysite.settingsStarting development server at

Quit the server with CONTROL-C.这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问 既然服务器已经运行起来了,现在用网页浏览器访问 你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。

你也可以指定启动端口:$ python manage.py runserver 8080以及指定 ip:$ python manage.py runserver 0.0.0.0:80003. 创建 app

前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块在项目目录下创建一个 app:$ python manage.py startapp polls如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:。

polls├── __init__.py├── admin.py├── migrations│ └── __init__.py├── models.py├── tests.py└── views.py

1 directory, 6 files4. 创建模型每一个 Django Model 都继承自 django.db.models.Model在 Model 当中每一个属性 attribute 都代表一个 database field

通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句打开 polls 文件夹下的 models.py 文件创建两个模型:import datetimefrom django.db import models。

from django.utils import timezoneclass Question(models.Model): question_text = models.CharField(max_length=200)

pub_date = models.DateTimeField(date published) def was_published_recently(self): return self.pub_date = timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200)

votes = models.IntegerField(default=0)然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:INSTALLED_APPS = (

django.contrib.admin, django.contrib.auth, django.contrib.contenttypes, django.contrib.sessions,

django.contrib.messages, django.contrib.staticfiles, polls,)在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:

$ python manage.py makemigrations polls你会看到下面的输出日志:Migrations for polls: 0001_initial.py: - Create model Choice

- Create model Question - Add field question to choice你可以从 polls/migrations/0001_initial.py 查看迁移语句。

运行下面语句,你可以查看迁移的 sql 语句:$ python manage.py sqlmigrate polls 0001输出结果:BEGIN;CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));

INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";

DROP TABLE "polls_choice";ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");

COMMIT;你可以运行下面命令,来检查数据库是否有问题:$ python manage.py check再次运行下面的命令,来创建新添加的模型:$ python manage.py migrateOperations to perform:

Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations: Applying polls.0001_initial... OK

总结一下,当修改一个模型时,需要做以下几个步骤:修改 models.py 文件运行 python manage.py makemigrations 创建迁移语句运行 python manage.py migrate,将模型的改变迁移到数据库中

你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法创建了模型之后,我们可以通过 Django 提供的 API 来做测试运行下面命令可以进入到 python shell 的交互模式:。

$ python manage.py shell下面是一些测试: from polls.models import Question, Choice # Import the model classes we just wrote.

# No questions are in the system yet. Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so

# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.

from django.utils import timezone q = Question(question_text="Whats new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.

q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending# on which database youre using. Thats no biggie; it just means your

# database backend prefers to return integers as Python long integer# objects. q.id1# Access model field values via Python attributes.

q.question_text"Whats new?" q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=UTC)# Change values by changing the attributes, then calling save().

q.question_text = "Whats up?" q.save()# objects.all() displays all the questions in the database. Question.objects.all()

[Question: Question object]打印所有的 Question 时,输出的结果是 [Question: Question object],我们可以修改模型类,使其输出更为易懂的描述修改模型类:。

from django.db import modelsclass Question(models.Model): # ... def __str__(self): # __unicode__ on Python 2

return self.question_textclass Choice(models.Model): # ... def __str__(self): # __unicode__ on Python 2

return self.choice_text接下来继续测试: from polls.models import Question, Choice# Make sure our __str__() addition worked.

Question.objects.all()[Question: Whats up?]# Django provides a rich database lookup API thats entirely driven by

# keyword arguments. Question.objects.filter(id=1)[Question: Whats up?] Question.objects.filter(question_text__startswith=What)

[Question: Whats up?]# Get the question that was published this year. from django.utils import timezone

current_year = timezone.now().year Question.objects.get(pub_date__year=current_year)Question: Whats up?

# Request an ID that doesnt exist, this will raise an exception. Question.objects.get(id=2)Traceback (most recent call last):

...DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a

# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1). Question.objects.get(pk=1)

Question: Whats up?# Make sure our custom method worked. q = Question.objects.get(pk=1)# Give the Question a couple of Choices. The create call constructs a new

# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates

# a set to hold the "other side" of a ForeignKey relation# (e.g. a questions choice) which can be accessed via the API.

q = Question.objects.get(pk=1)# Display any choices from the related object set -- none so far. q.choice_set.all()

[]# Create three choices. q.choice_set.create(choice_text=Not much, votes=0)Choice: Not much q.choice_set.create(choice_text=The sky, votes=0)

Choice: The sky c = q.choice_set.create(choice_text=Just hacking again, votes=0)# Choice objects have API access to their related Question objects.

c.questionQuestion: Whats up?# And vice versa: Question objects get access to Choice objects. q.choice_set.all()

[Choice: Not much, Choice: The sky, Choice: Just hacking again] q.choice_set.count()3# The API automatically follows relationships as far as you need.

# Use double underscores to separate relationships.# This works as many levels deep as you want; theres no limit.

# Find all Choices for any question whose pub_date is in this year# (reusing the current_year variable we created above).

Choice.objects.filter(question__pub_date__year=current_year)[Choice: Not much, Choice: The sky, Choice: Just hacking again]

# Lets delete one of the choices. Use delete() for that. c = q.choice_set.filter(choice_text__startswith=Just hacking)

c.delete()上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM5. 管理 adminDjango有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.。

新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:INSTALLED_APPS = ( django.contrib.admin, #默认添加后台管理功能 django.contrib.auth,

django.contrib.contenttypes, django.contrib.sessions, django.contrib.messages, django.contrib.staticfiles,

mysite,)同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:url(r^admin/, include(admin.site.urls)), #可以使用设置好的url进入网站后台

接下来我们需要创建一个管理用户来登录 admin 后台管理界面:$ python manage.py createsuperuserUsername (leave blank to use june): admin

Email address:Password:Password (again):Superuser created successfully.总结最后,来看项目目录结构:mysite├── db.sqlite3

├── manage.py├── mysite│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ ├── wsgi.py├── polls│ ├── __init__.py

│ ├── admin.py│ ├── migrations│ │ ├── 0001_initial.py│ │ ├── __init__.py│ ├── models.py

│ ├── templates│ │ └── polls│ │ ├── detail.html│ │ ├── index.html│ │ └── results.html

│ ├── tests.py│ ├── urls.py│ ├── views.py└── templates └── admin └── base_site.htm

通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识django中的migrate怎么迁移数据到数据库中。

database migrations 是laravel最强大的功能之一数据库迁移可以理解为数据库的版本控制器在 database/migrations 目录中包含两个迁移文件,一个建立用户表,一个用于用户密码重置。

在迁移文件中,up 方法用于创建数据表,down方法用于回滚,也就是删除数据表结语:以上就是首席CTO笔记为大家介绍的关于django迁移数据库在哪里的全部内容了,希望对大家有所帮助,如果你还想了解更多这方面的信息,记得收藏关注本站。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:怎么学习TiDB,一站式学习指南
下一篇:了解网络数据传输的安全挑战
相关文章