一半教程用的Django都是1.8以前的版本,导致跟我用的1.8.2的版本用法有些出入,所以只能自己去官网看文档,以下一下是看官方文档而理解的,英语渣渣,可能会有理解有误的地方
先记录下如何查看django的版本:
>>>python
>>>import django
>>>django.VERSION
(1, 8, 2, 'final', 0)
把官网的那段示例Model copy过来,为了加深印象,我自己会手写一边:
from django.db import models class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField() def __str__(self): # __unicode__ on Python 2
return self.name class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField() def __str__(self): # __unicode__ on Python 2
return self.name class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField() def __str__(self): # __unicode__ on Python 2
return self.headline
抄完结果结构后在dos虚拟环境下我们来验证下有没有错误:
>>>python manage.py check
System check identified no issues ( 0 silenced).
表示没错,接下来生成数据库迁移文件(未同步到数据库):
>>>python manage.py makemigrations --name frist
Migrations for 'myLesson'__frist.py:
- Create model Author
- Create model Blog
- Create model Entry
--name 后面为此次迁移标识的名字,最终生成0001_frist.py,该文件在app目录下/migrations
最后我们来同步下更改
>>>python manage.py migrate
....省略
Applying sessions.001_initital... OK
我用的默认配置的Sqlite3数据库,使用Navicat打开如下:
红框内是Django为我们定义的实体生成的表
---吃饭先