django数据库迁移?如何解决Django 1.8在migrate时失败
大家好,今天小编来为大家解答django数据库迁移这个问题,如何解决Django 1.8在migrate时失败很多人还不知道,现在让我们一起来看看吧!
django是前端还是后端
演示机型:华为MateBookX系统版本:win10
APP版本:django3.0django是用在前端。Django是一个基于Python的Web应用框架。它与Python的另外一个Web框架Flask最大的区别是,它奉行“包含一切”的哲学。该理念即为创建Web应用所需的通用功能都应该包含到框架中,而不应存在于独立的软件包中。例如身份验证、URL路由、模板系统、对象关系映射(ORM)和数据库迁移等功能都已包含在Django框架中。虽然看上去失去了一些弹性,但是却可以在构建网站的时候更加有效率。
Django是什么
Django是一个开源的python Web框架,用于快速开发,实用,可维护,简洁的设计,并保护网站。Web应用程序框架是应用程序开发所需的所有组件的工具包。Django框架的主要目标是允许开发人员专注于新应用程序的组件,而不是花时间在已开发的组件上。Django是市场上许多其他框架的完整功能。它解决了Web开发中涉及的大量麻烦;使用户能够专注于开发其应用程序所需的组件。
Django的十大用途
1. Django经过时间考验
Django已经花了13年的时间来开发它的框架和第一个开源提交版本,因为它在发布之前很长一段时间都在开发中。在这些年中,它发布了很多版本,其中一些有新特性,其他版本侧重于安全增强等。Django是第一个响应新问题和漏洞的框架,并修改其他框架以对框架进行补丁。它的最新版本主要关注新特性和边界用例问题。
2.应用程序开发
Django是由在线新闻运营团队开发的,目的是使用Python编程语言创建web应用程序。这个框架有模板、库和api,它们一起工作。一般来说,使用Django开发的应用程序可以以最小的成本、更改和添加进行升级,这使得许多web开发变得更加容易。
3.易于使用
Django使用Python编程语言,Python编程语言是2015年的流行语言,目前大多数学习Django框架编程和应用的程序员选择的语言都被广泛使用,因为Django框架是免费和开源的,由大量开发人员社区开发和维护。这意味着我们可以很容易地使用谷歌找到问题的答案。
4.操作系统依赖
Django框架可以在PC、Windows、Mac、Linux等任何平台上运行。它在开发人员和数据库之间提供了一个名为ORM(object-relational mapper,对象关系映射器)的层,这使得我们可以在不需要修改几行代码的情况下将应用程序迁移到其他主要数据库。
5.针对实际应用的优秀文档
Django的应用程序拥有其框架的最佳文档之一,用于开发不同类型的实际应用程序,而许多其他框架使用按字母顺序排列的模块,属性和方法列表。当我们在两个方法或模块之间混淆时,这对于开发人员的快速参考非常有用,但对于第一次学习的新手来说则不是。Django开发人员维护文档质量是一项艰巨的任务,因为它是任何框架的最佳开源文档之一。
6.可扩展且可靠
由于Django是一个维护良好的Web应用程序框架,并且在各个行业中广泛使用,因此云提供商采取一切措施为在云平台上轻松快速地运行Django应用程序提供支持。这意味着,一旦部署了Django应用程序,它就可以由授权开发人员在云环境中使用单个命令进行管理。由于Django开发人员长期在相同的开发环境中工作,因此他们将在这些领域发展和专业知识,这意味着应用程序的开发,创建的网站日益完善,功能更强,更高效,更可靠。
7.社区支持
Django社区是最好的社区之一,因为它由Django软件基金会管理,该基金会有一些规则,比如有一个行为准则的事件。Django社区将对IRC和邮件列表表示欢迎,即使它可能会有不良的上诉,它会立即纠正。Django提供稳定性,包,文档和良好的社区。
8.不要重复自己
Django框架遵循不重复自己的原则,因为它专注于充分利用每行代码,通过这些代码,我们可以花更少的时间进行调试或代码重定向等。通常DRY代码意味着数据的所有使用同时改变而不是需要复制,而是在所有编程中使用变量和函数的根本原因。
9. Django的电池
Django框架可以构建一个强大的框架,其主要功能如下:
模板图层,
形式,发展过程,
视图层,安全性,
模型层,python兼容性,
本地化,性能和优化
地理框架,Web应用程序开发的常用工具
网站所需的其他核心功能。
由于Django可以用来构建任何类型的网站,包括内容管理,维基百科页面,社交网络应用程序,聊天应用程序以及Mozilla,Instagram,Pinterest,BitBucket等网站.Django可以与任何客户端-服务器一起使用应用程序并能够以任何形式(HTML,文本,JSON,XML,RSS等)提供内容
10. Django的好处
通过使用Django框架,我们可以在几小时内开发和部署Web应用程序,因为它可以解决Web开发的大部分麻烦。Django非常快速,满载,例如它负责用户身份验证,内容管理,安全性,因为Django非常重视并有助于避免SQL注入,跨站点脚本等等,并且可扩展,因为应用程序可以扩展以满足高要求并且用于构建任何类型的应用程序,这就是我们将其称为多功能框架的原因。我们可以使用Django框架构建从内容管理到社交网站的不同应用程序。它提供了大量资源和良好的文档,可以帮助新学员学习和体验人员,以供参考。
结论- Django的使用
最后,本文概述了Django、我们需要如何使用它,以及它在实际应用程序开发中的用途。我希望您在阅读了Django的这篇文章之后,能够对Django框架有一个很好的了解。由于Django框架是通用的,它允许开发人员专注于业务逻辑,而不是编写由Django本身处理的公共实用程序。因此,如果您需要在短时间内以完全安全的方式完成web应用程序或网站,并提供基于流量的快速、可靠和可伸缩的服务,请选择Django。很多好的网站都是用Django框架开发的,比如Instagram, BitBucket, Mozilla等等。
如何解决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= 1
LANGUAGE_CODE='zh_CN'
TIME_ZONE='Asia/Shanghai'
USE_TZ= True
上面开启了 [Time zone](https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/)特性,需要安装 pytz:
$ sudo pip install pytz
2.运行项目
在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running 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:33
Django version 1.7.1, using settings'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
这将会在端口8000启动一个本地服务器,并且只能从你的这台电脑连接和访问。既然服务器已经运行起来了,现在用网页浏览器访问 http://127.0.0.1:8000/。你应该可以看到一个令人赏心悦目的淡蓝色 Django欢迎页面它开始工作了。
你也可以指定启动端口:
$ python manage.py runserver 8080
以及指定 ip:
$ python manage.py runserver 0.0.0.0:8000
3.创建 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 files
4.创建模型
每一个 Django Model都继承自 django.db.models.Model
在 Model当中每一个属性 attribute都代表一个 database field
通过 Django Model API可以执行数据库的增删改查,而不需要写一些数据库的查询语句
打开 polls文件夹下的 models.py文件。创建两个模型:
import datetime
from django.db import models
from django.utils import timezone
class 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 migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running 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="What's 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 you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text="What's 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 models
class Question(models.Model):
#...
def __str__(self):# __unicode__ on Python 2
return self.question_text
class 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: What's up?>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's 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: What's up?>
# Request an ID that doesn't 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: What's 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 question's 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.question
<Question: What's 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; there's 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>]
# Let's delete one of the choices. Use delete() for that.
>>> c= q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
>>>
上面这部分测试,涉及到 django orm相关的知识,详细说明可以参考 Django中的ORM。
5.管理 admin
Django有一个优秀的特性,内置了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 createsuperuser
Username(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
OK,本文到此结束,希望对大家有所帮助。