美文网首页
二、编辑blog应用的models.py

二、编辑blog应用的models.py

作者: 途中的蜗牛 | 来源:发表于2020-12-30 09:01 被阅读0次

models.py,类似于定义数据库中的数据表,每个属性对应一个字段。

1、创建新表

1.1、修改models.py

该文件路径./blog/models.py

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 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    # author规定了作者和用户之间的关系,ForeignKey()是“一对多”的关系。related_name运行通过类User反向查询到BlogArticles
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ('-publish',)  # 注意有',' 按照publish字段值的倒序显示。

    def __str__(self):
        return self.title

1.2、创建表结构

$ python manage.py makemigrations  # 在blog/migrations中创建了BlogArticles模型
Migrations for 'blog':
  blog/migrations/0001_initial.py
    - Create model BlogArticles

可以使用如下命令查看相应的SQL语句。

$ python manage.py sqlmigrate blog 0001
BEGIN;
--
-- Create model BlogArticles
--
CREATE TABLE `blog_blogarticles` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(300) NOT NULL, `body` longtext NOT NULL, `publish` datetime(6) NOT NULL, `author_id` integer NOT NULL);
ALTER TABLE `blog_blogarticles` ADD CONSTRAINT `blog_blogarticles_author_id_ed798e23_fk_auth_user_id` FOREIGN KEY (`author_id`) REFERENCES `auth_user` (`id`);
COMMIT;

1.3、创建数据库

$ python manage.py migrate

执行该命令后,数据库会多生成了一个表blog_blogarticles

2、使用原有的表

2.1 针对已有数据库自动生成新的models

原有的表最好有个id的主键(PRIMARY KEY,一般可设置为自动增加)或者是其他的主键(PRIMARY KEY):

  `id` int(50) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`),

获取原有表mytable的models.py脚本文件:

$ python manage.py inspectdb > models.py

除去Django自动创建的数据表以外,截取剩下自己创建的数据表信息,默认会隐去id字段:

class Mytable(models.Model):
    title = models.CharField(max_length=50, blank=True, null=True)
    href = models.CharField(max_length=200, blank=True, null=True)
    date = models.CharField(max_length=20, blank=True, null=True)
    content_body = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'mytable'
  • 默认配置下生成不可修改/删除的models,修改meta class中的managed=True则告诉django可以对数据库进行操作

2.2执行语句

$ python manage.py makemigrations
$ python manage.py migrate

3、发布博客文章

3.1 创建超级用户

$ python manage.py createsuperuser
用户名 (leave blank to use 'test'): admin
电子邮件地址: admin@admin.com
Password: 
Password (again): 

3.2、运行服务器

$ python manage.py runserver

在浏览器中输入http://127.0.0.1:8000/admin/登录超级用户,登录之后可以看到如下的用户管理界面:

用户管理界面

但是看不到博客文章,因此需要在./blog/admin.py中添加BlogArticles

from django.contrib import admin
from .models import BlogArticles

class BlogArticlesAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "publish")
    list_filter = ("publish", "author")
    search_fields = ("title", "body")
    raw_id_fields = ("author",)
    date_hierarchy = "publish"
    ordering = ['-publish', 'author']

admin.site.register(BlogArticles, BlogArticlesAdmin)

这时候就可以看到blog的栏目了,添加增加就可以新增文章了。

相关文章

网友评论

      本文标题:二、编辑blog应用的models.py

      本文链接:https://www.haomeiwen.com/subject/xffqoktx.html