django_2数据库CRUD

auth:xiangxianzhang 

Date:2018-4-23

Email:550276107@qq.com

GitHub:https://github.com/xxz199539/notebook

数据库插入数据准备

  1. 创建超级管理员的账号密码
  2. python manage.py createsuperuser

ORM 对象关系映射,翻译机
对象关系映射(Object Relational Mapping,简称ORM)是为了解决面向对象与关系型数据库存在的互不匹配的现象的技术。本质上就是将数据从一种形式转换到另外一种形式。 这也同时暗示着额外的执行开销;然而,如果ORM作为一种中间件实现,则会有很多机会做优化,而这些在手写的持久层并不存在。 更重要的是用于控制转换的元数据需要提供和管理。
实际应用中即在关系型数据库和业务实体对象之间作一个映射,这样,我们在具体的操作业务对象的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作它就可以了。

  1. 模型字段
CharField: 字符串
BooleanField:布尔类型
DateField: 年月日,日期
auto_now_add: 第一次创建的时候赋值
auto_now:每次修改的时候赋值

AutoField:自动增长
DecimalField: 
models.DecimalField(max_digits=3, decimal_places=1)
max_digits:总位数
decimal_places:小数后多少位

TextField:存文本信息
IntegerField:整数
FloatField:浮点

FileField:文件上传字段
ImageField:上传图片
  upload_to="" 指定上传图片的路径
  1. 模型参数
default: 默认
null :设置是否为空,针对数据库中该字段是否可以为空
blank :设置是否为空,针对表单提交该字段是否可以为空
primary_key:创建主键
unique:唯一

插入数据

1.form表单提交post请求数据

<form action="stuapp/addstu" method="post">
        <table>
            <tr>
                <td>姓名</td>
                <td>性别</td>
                <td>生日</td>
                <td>电话</td>
                <td>语文成绩</td>
                <td>数学成绩</td>
                <td>班级编号</td>

            </tr>
            <tr>
                <td><input type="text" name="name"></td>
                <td><input type="text" name = "sex"></td>
                <td><input type="date" name = "birth"></td>
                <td><input type="text" name = "tel"></td>
                <td><input type="text" name = "yuwen"></td>
                <td><input type="text" name = "math"></td>
                <td><input type="text" name = "num"></td>
            </tr>
        </table>
        <input type="submit" value="提交">
    </form>

2.获取post请求,获取请求数据,并且创建数据
第一种方法:

# stu = Student()
# stu.stu_name = stu_name
# stu.stu_birth = stu_birth
# stu.stu_sex = stu_sex
# stu.stu_tel = stu_tel
# stu.save()

第二种方法:

Student.objects.create(
    stu_name=stu_name,
    stu_birth=stu_birth,
    stu_sex=stu_sex,
    stu_tel=stu_tel,
    stu_yuwen =stu_yuwen,
    stu_math = stu_math,
    stu_num = stu_num

)

3.查询所需数据

stus = Student.objects.all()
stus = Student.objects.filter(stu_sex=False)#s筛选
stus = Student.objects.all().order_by('-id')#排序
stus = Student.objects.all().order_by('-id').last#最后一个,first是第一个
stus = Student.objects.filter(stu_sex=True).count()
stus = Student.objects.filter(stu_sex=False).\
filter(stu_birth__gte='1980-01-01').filter(stu_birth__lte='1990-01-01')
#取出年纪大于1980-01-01小于1990-01-01的女生
stus = Student.objects.filter(stu_name__startswith='李')#查询以李开头的数据
stus = Student.objects.filter(stu_name__endwith='华')  # 查询以华结束的数据
stus = Student.objects.filter(stu_name__contains='华')  # 查询包含华的数据
stus = Student.objects.filter(stu_name='张三').exists()#查询数据库中是否有张三的数据
ids=[1,2]
stus = Student.objects.filter(stu__in=ids)#选取到多个id的数据

猜你喜欢

转载自blog.csdn.net/qq_41768400/article/details/80207469