Django项目流程

  • 创建项目和应用

django-admin.py startproject project_name
cd project_name
python manage.py startapp app_name

添加 app_name 到 settings.py 中的 INSATLLED_APPS 中。

  • 规划写models.py

示例:

from __future__ import unicode_literals
 
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
 
 
@python_2_unicode_compatible
class Column(models.Model):
    name = models.CharField('栏目名称', max_length=256)
    slug = models.CharField('栏目网址', max_length=256, db_index=True)
    intro = models.TextField('栏目简介', default='')
 
    def __str__(self):
        return self.name
 
    class Meta:
        verbose_name = '栏目'
        verbose_name_plural = '栏目'
        ordering = ['name']  # 按照哪个栏目排序
 
 
@python_2_unicode_compatible
class Article(models.Model):
    column = models.ManyToManyField(Column, verbose_name='归属栏目')
 
    title = models.CharField('标题', max_length=256)
    slug = models.CharField('网址', max_length=256, db_index=True)
 
    author = models.ForeignKey('auth.User', blank=True, null=True, verbose_name='作者')
    content = models.TextField('内容', default='', blank=True)
 
    published = models.BooleanField('正式发布', default=True)
 
    def __str__(self):
        return self.title
 
    class Meta:
        verbose_name = '教程'
        verbose_name_plural = '教程'

 

  • 创建数据库

python manage.py makemigrations news
python manage.py migrate
  • 更改models.py

对models.py进行更改后,更改字段数据库中没有,需要同步更改到数据库中。

python manage.py makemigrations news

后续操作:

You are trying to add a non-nullable field 'pub_date' to article without a default; we can't do that (the database needs something to populate existing rows).

Please select a fix:

 1) Provide a one-off default now (will be set on all existing rows)

 2) Quit, and let me add a default in models.py

这段话的意思是 pub_date 字段没有默认值,而且非Null 那么 

1) 指定一个一次性的值供更改数据库时使用。

2) 停止当前操作,在 models.py 中给定默认值,然后再来migrate。

我们选择第一个,输入 1

Select an option: 1

Please enter the default value now, as valid Python

The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()

>>> timezone.now()

Migrations for 'news':

  0002_auto_20150728_1232.py:

    - Add field pub_date to article

    - Add field update_time to article

这样是生成了一个对表进行更改的 py 文件在 news/migrations 文件夹中,我们要执行更改

python manage.py migrate 或 python manage.py migrate news
  • 创建脚本,导入数据到数据库中

示例:

'''
create some records for demo database
'''
 
from minicms.wsgi import *
from news.models import Column, Article
 
 
def main():
    columns_urls = [
      ('体育新闻', 'sports'),
      ('社会新闻', 'society'),
      ('科技新闻', 'tech'),
    ]
 
    for column_name, url in columns_urls:
        c = Column.objects.get_or_create(name=column_name, slug=url)[0]
 
        # 创建 10 篇新闻
        for i in range(1, 11):
            article = Article.objects.get_or_create(
                title='{}_{}'.format(column_name, i),
                slug='article_{}'.format(i),
                content='新闻详细内容: {} {}'.format(column_name, i)
            )[0]
 
            article.column.add(c)
 
 
if __name__ == '__main__':
    main()
    print("Done!")

运行脚本 导入数据:

python create_demo_records.py

 

posted @ 2016-08-18 09:15  dear_diary  阅读(381)  评论(0编辑  收藏  举报