django-模型之(ORM)对象关系映射(一)
所谓对象关系映射,就是将数据库的一些名字与python中的一些名字相对应,表名-->类名,字段-->属性,操作(增删改查)-->方法。这样,我们就可以通过对Python代码的编辑来对数据库进行操作。
流程:创建models,通过models创建迁移文件(makemigrations),通过迁移文件映射到数据库中。
book/models.py
from django.db import models # Create your models here. class Student(models.Model): #字段映射,数据库中是male,female,后台显示的是男,女 choices={ ('male',"男"), ('female','女'), } #创建数据库中的字段 name=models.CharField(verbose_name='姓名',max_length=20,unique=True) age=models.CharField(verbose_name='年龄',max_length=10) gender=models.CharField(verbose_name='性别',max_length=10,choices=choices,default='male') is_deleted=models.BooleanField(default=False) introduce=models.TextField() def __str__(self): return self.name class Meta: # verbose_name_plural='新闻' # verbose_name="新闻列表" #修改排列的顺序,这句是靠id从大到小排序 ordering=['-id'] db_table = 'student'
book/admin.py
from django.contrib import admin from .models import Student # Register your models here. #在后台显示相关信息 class StudentAdmin(admin.ModelAdmin): list_display = ['id','name','age','gender','is_deleted','introduce'] #将模型进行注册 admin.site.register(Student,StudentAdmin)
有了这两个,输入:
python manage.py makemigrations
python manage.py migrate
会在migrations下生成一个文件:
具体内容如下:
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0001_initial'), ] operations = [ migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, unique=True, verbose_name='姓名')), ('age', models.CharField(max_length=10, verbose_name='年龄')), ('gender', models.CharField(choices=[('male', '男'), ('femal', '女')], max_length=10, verbose_name='性别')), ('is_deleted', models.BooleanField(default=False)), ('introduce', models.TextField()), ], ), migrations.DeleteModel( name='Articles', ), ]
我们要进入后台管理界面需要设置用户名和密码:
python manage.py createsuperuser
输入用户:admin 密码:12345678 邮箱可以不填
浏览器输入127.0.0.1:8000/admin,输入账号密码后进入到管理界面,
点击students,会有相应表的信息:
最后,我们将数据库里面的内容传到前台页面:
book/views.py
from .models import Student from django.shortcuts import render def index(request): student_list=Student.objects.all() context={ 'students':student_list, } return render(request,"index.html",context=context)
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{title}}</title> <link rel="stylesheet" href={% static 'css/index.css' %}> </head> <body> {% include 'header.html'%} <div class="content"> <h1>这是主界面</h1> {% for student in students %} {{student.id}} {{student.name}} {% endfor %} <!--{% block content %}--> <!--{% endblock %}--> </div> {% include 'footer.html'%} </body> </html>
最终效果: