Django编写博客的数据模型类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/85015322

一 点睛

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

二 编写博客的数据模型类

三 编写数据模型类

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class BlogArticles(models.Model):
    title = models.CharField(max_length=300)
    # 通过author规定了博客文章和用户之间的关系——一个用户对于多篇文章,
    # ForeignKey()就反映了这种“一对多”关系。类User就是BlogArticle的对应对象,
    # related_name='blog_posts'的作用是允许通过反向查询到BlogArticles
    author = models.ForeignKey(User, related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    # 通过ordering = ("-publish",),规定了BlogArticles实例对象的显示顺序,即按照publish
    # 字段值倒序显示。
    class Meta:
        ordering = ("-publish",)

    def __str__(self):
        return self.title

四 生成数据库表结构指令

(venv) E:\Django\mysite\mysite>python manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model BlogArticles

五 查看生成的文件0001_initial.py

# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2018-12-15 08:13
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='BlogArticles',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=300)),
                ('body', models.TextField()),
                ('publish', models.DateTimeField(default=django.utils.timezone.now)),
                ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('-publish',),
            },
        ),
    ]

六 通过命令查看0001_initial.py文件本质

(venv) E:\Django\mysite\mysite>python manage.py sqlmigrate blog 0001
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"));
CREATE INDEX "blog_blogarticles_author_id_ed798e23" ON "blog_blogarticles" ("author_id");
COMMIT;

七 创建数据库

(venv) E:\Django\mysite\mysite>python manage.py migrate
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 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 blog.0001_initial... OK
  Applying sessions.0001_initial... OK

八 查看数据库生成结果

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/85015322