软件测试之路测试Inbox

Django之旅:3

2018-01-09  本文已影响4人  五娃儿

包含内容

数据模型类

在应用的models.py中创建数据库类模型,通过migrate等命令,实现对应的模型

models.py

from django.db import models
from django.utils import timezone

# Create your models here.
from django.contrib.auth.models import User


class BlogArticles(models.Model):
    title = models.CharField(max_length = 300)
    author = models.ForeignKey(User, related_name="blog_posts")
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ("-publish",)

    def __str__(self):
        return self.title

在cmd中执行 python manage.py makemigrations,生成BlogArticles的模型


执行结果.jpg

在migrations文件夹下会生成对应的模型
0001——initial.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

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


class Migration(migrations.Migration):

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

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

连接数据库后,查看blog_blogarticles(应用名_模型类名小写),创建成功


数据库结果.jpg

对比模型类和数据表


对比结果jpg

通过对比结果可以看出来,model的属性对应的是表中字段的类型、长度等关系

知识点

1、注册应用
2、编写模型类 models.py文件
3、创建模型 python manage.py makemigrationgs
4、创建表结构 python manage.py migrate
5、理解模型的属性和数据库中表的属性的对应关系

上一篇 下一篇

猜你喜欢

热点阅读