博客五部曲之一 - 简单博客


1271 浏览 5 years, 4 months

6 第一个应用和Module

版权声明: 转载请注明出处 http://www.codingsoho.com/

我们首先创建一个自己的app posts来处理博客相关的内容。

python manage.py startapp posts

自动创建posts app,在当前工作目录下创建一个posts文件夹

│  admin.py
│  apps.py
│  models.py
│  tests.py
│  views.py
│  __init__.py
│
└─migrations
       __init__.py

在models.py文件添加post类定义

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()    
    updated = models.DateTimeField(auto_now=False, auto_now_add=True)
    timestap = models.DateTimeField(auto_now=True, auto_now_add=False)
    def  __unicode__(self):
        return self.title
    # # python3
    def __str__(self):
        return self.title

同时,在settings.py里添加对应的app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'posts',
]

添加新的数据定义后,需要再次同步数据库

首先运行makemigrations生成数据库同步命令文件,它会在migrations目录下面生成对应的文件。

python manager.py makemigrations

然后执行migrate写入数据库

python manager.py migrate

其他的一些model类型可以查看https://docs.djangoproject.com/en/1.11/ref/models/fields/