zoukankan      html  css  js  c++  java
  • django_4:数据库1——django操作数据库

    创建数据库记录(插入)

    使用python3 manage.py shell(python3亲测好使)

    ipython3 manage.py shell(亲测不好使)

    方式一、

    [root@centos7 csvt03]# python3 manage.py shell
    Python 3.5.2 (default, May  9 2017, 23:04:15) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: from blog.models import Employee
    
    In [2]: Employee
    Out[2]: blog.models.Employee
    
    In [3]: emp = Employee()    #创建实例
    
    In [4]: emp.name = 'Alen'    #在实例中修改字段属性,进行复制
    
    In [5]: emp.save()        #保存
    
    In [6]: 
    此时去数据库查看就能看到新创建的记录信息了
    修改py文件后,在这里怎么reload???

    方法二、

    In [6]: emp = Employee(name='Tom')  #创建时直接复制
    
    In [7]: emp.save()

     方法三、

    In [9]: Employee.objects.create(name='Max')    #通过类调用他的管理器
    Out[9]: <Employee: Employee object>       #返回值是一个对象

    查询数据库记录

    In [11]: emps = Employee.objects.all()      #获得所有对象
    
    In [12]: emps                     #不能直观看出,可以使用__str__ __repr__,视频中使用的是__unicode__,所以去修改model.py
    Out[12]: <QuerySet [<Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>]>
    
    In [13]: emps[0].id
    Out[13]: 1
    
    In [14]: emps[0].name
    Out[14]: 'Alen'

    在views.py中操作数据库

    from django.shortcuts import render
    from blog.models import Employee
    
    # Create your views here.
    def index(req):
        emps = Employee.objects.all()
        return render(req, 'index.html', {'emps':emps})
  • 相关阅读:
    python_day16_闭包_装饰器
    高阶函数_递归函数_内置函数
    python_day14_函数_返回值_局部和全局变量
    python_day14_set_回到了python的学习
    grep_sed_awl_vim
    jQuery学习之选择器
    css3之其他的属性
    css3之响应式
    css3之各种布局
    css3之各种变形
  • 原文地址:https://www.cnblogs.com/daduryi/p/6837200.html
Copyright © 2011-2022 走看看