温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Django怎么编写数据模型类

发布时间:2021-11-15 17:00:01 来源:亿速云 阅读:166 作者:iii 栏目:大数据

本篇内容介绍了“Django怎么编写数据模型类”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

设计数据库和表结构是做网站的基础。在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

“Django怎么编写数据模型类”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI