《Django By Example》读书笔记 02

项目(Projects)和应用(applications)的区别
在Django中,项目是一个大的集合,应用是项目的一个模块,例如模板,视图,URL等和framework交互,提供某种特定功能,可复用。

创建一个应用

python manage.py startapp blog

在同级目录会看到blog文件夹,
这里写图片描述

admin.py: 将blog注册到Django administration site。
migrations: 放置应用的数据库,允许Django追踪模型变化,同步数据库。
models.py: 应用数据模型,Django应用都要有这个文件,文件内容可以为空。
tests.py: 在此添加应用测试。
views.py: 接收处理http请求,返回相应。

设计blog的数据结构
在models.py添加以下代码

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
    STATUS_CHOICES = (
    ('draft', 'Draft'),
    ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
    unique_for_date='publish')
    author = models.ForeignKey(User,
    related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
    choices=STATUS_CHOICES,
    default='draft')
    class Meta:
    ordering = ('-publish',)
    def __str__(self):
    return self.title

这里是blog的post基础模型

  1. title:post的title,CharField类型,会转成SQL数据库的VARCHAR column
  2. SlugField只能包含字母,数字,下划线和连字符的字符串,通常被用于URLs表示。
  3. author: This field is ForeignKey. This field defines a many-to-one relationship. We are telling Django that each post is written by a user and a user can write several posts. For this field, Django will create a foreign key in the database using the primary key of the related model. In this case, we are relying on the User model of the Django authentication system. We specify the name of the reverse relationship, from User to Post, with the related_name attribute. We are going to learn more about this later.
  4. body: This is the body of the post. This field is TextField, which translates into a TEXT column in the SQL database.
  5. publish: This datetime indicates when the post was published. We use Django’s timezone now method as default value. This is just a timezone-aware datetime.now.
  6. created: This datetime indicates when the post was created. Since we
    are using auto_now_add here, the date will be saved automatically when
    creating an object.
    updated: This datetime indicates the last time the post has been updated.
    Since we are using auto_now here, the date will be updated automatically
    when saving an object.
    status: This is a field to show the status of a post. We use a choices
    以上内容懒得翻译了,自己看吧
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章