简单的博客系统(二)Django编写数据模型类

原创
2019/07/20 19:18
阅读数 369

设计数据库和表结构是做网站的基础。在Django中,不需要通过SQL语句直接跟数据库打交道,而是完全用Python的类来创建数据模型,之后交给Django完成创建数据库的操作。

数据模型类

数据模型类需要在 应用目录 下的 models.py 文件中编写

编写数据模型

  • 下面的代码演示了在 models.py 中定义了一个博客文章的类
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


# Create your models here.
class BlogArticles(models.Model):  # Django中的数据模型类都继承自 django.db.models.Model类
    # 字段 title 的属性为 CharField 类型,并且参数长度为 300
    title = models.CharField(max_length=300)
    """
    字段 author 使用 ForeignKey 规定了博客文章和用户之间的关系:一个用户对应多篇文章
    models.CASCADE 表示级联删除
    related_name="blog_posts" 表示允许User类的实例以 "blog_posts" 属性反向查询到BlogArticles类的实例
    """
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    """
    ordering = ("-publish",) 规定BlogArticles类的实例按 publish 字段值倒序显示
    """
    class Meta:
        ordering = ("-publish",)

    """
    重写父类的方法,使得当使用 str()函数转换该类的实例为字符串时,返回 title 属性的值
    """
    def __str__(self):
        return self.title

根据数据模型建立数据库表

  1. 创建数据库表文件
E:\PycharmProjects\demosite>python manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0002_auto_20190720_1919.py
    - Alter field publish on blogarticles
  1. 上面执行结果的提示信息中,告诉我们在 blog/migrations 目录中创建了一个 BlogArticles模型,模型编号为 0001。可以输入以下命令查看相对应的SQL语句:
E:\PycharmProjects\demosite>python manage.py sqlmigrate blog 0001
System check identified some issues:

WARNINGS:
blog.BlogArticles.publish: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
BEGIN;
--
-- Create model BlogArticles
--
CREATE TABLE "blog_blogarticles" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(300) NOT NULL, "body" text NOT NULL, "publish" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "blog_blogarticles_author_id_ed798e23" ON "blog_blogarticles" ("author_id");
COMMIT;

在数据库中表名格式为:小写的应用名称_小写的类名称

  1. 创建数据库
(demosite) E:\PycharmProjects\demosite>python manage.py migrate
System check identified some issues:

WARNINGS:
blog.BlogArticles.publish: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部