django - model

python版本3.5

  到目前为止,我们所学的操作数据库可以用pymysql连接数据库,写原生sql语句或者使用sqlalchemy来操作数据库。

  在django下可以使用自带的ORM(关系对象映射,Object Relational Mapping),其增加了封装了更多的数据类型,功能也更强大,并遵循 Code Frist 的原则,即:根据代码中定义的类来自动生成数据库表。;但其封装的原生数据类型额外的数据类型在普通情况下并没有额外的功效,只是在Admin操作数据库是起限制作用。

如:
email = models.EmailFeild()

此声明只是在Admin插入数据库时才起 格式限制作用不符合条件不能插入,不使用Admin时,EmailFeild 只相当于 CharFeild 。

 

1.创建数据表

django ORM遵循 一张表对应一个类的 设计原则

在model中写入类

from django.db import models

class UserInfo(models.Model):
    username = models.CharFeild(max_length=32)
    password = models.CharFeild(max_length=32)
    email = models.EmailFeild()
    ctime = models.DateTimeField(auto_time_add=True)
    mtime = models.DateTimeField(auto_time = True)

      """    
        class Meta:
            pass
    """
    """
    def __str__(self):
        return xxx
    """

  Meta的用法请看:http://www.cnblogs.com/yangxiaolan/p/5798474.html

 更多字段

1、models.AutoField  自增列 = int(11)
  如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。
2、models.CharField  字符串字段
  必须 max_length 参数
3、models.BooleanField  布尔类型=tinyint(1)
  不能为空,Blank=True
4、models.ComaSeparatedIntegerField  用逗号分割的数字=varchar
  继承CharField,所以必须 max_lenght 参数
5、models.DateField  日期类型 date
  对于参数,auto_now = True 则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。
6、models.DateTimeField  日期类型 datetime
  同DateField的参数
7、models.Decimal  十进制小数类型 = decimal
  必须指定整数位max_digits和小数位decimal_places
8、models.EmailField  字符串类型(正则表达式邮箱) =varchar
  对字符串进行正则表达式
9、models.FloatField  浮点类型 = double
10、models.IntegerField  整形
11、models.BigIntegerField  长整形
  integer_field_ranges = {
    'SmallIntegerField': (-32768, 32767),
    'IntegerField': (-2147483648, 2147483647),
    'BigIntegerField': (-9223372036854775808, 9223372036854775807),
    'PositiveSmallIntegerField': (0, 32767),
    'PositiveIntegerField': (0, 2147483647),
  }
12、models.IPAddressField  字符串类型(ip4正则表达式)
13、models.GenericIPAddressField  字符串类型(ip4和ip6是可选的)
  参数protocol可以是:both、ipv4、ipv6
  验证时,会根据设置报错
14、models.NullBooleanField  允许为空的布尔类型
15、models.PositiveIntegerFiel  正Integer
16、models.PositiveSmallIntegerField  正smallInteger
17、models.SlugField  减号、下划线、字母、数字
18、models.SmallIntegerField  数字
  数据库中的字段有:tinyint、smallint、int、bigint
19、models.TextField  字符串=longtext
20、models.TimeField  时间 HH:MM[:ss[.uuuuuu]]
21、models.URLField  字符串,地址正则表达式
22、models.BinaryField  二进制
23、models.ImageField   图片
24、models.FilePathField 文件

 更多参数

1、null=True
  数据库中字段是否可以为空
2、blank=True
  django的 Admin 中添加数据时是否可允许空值
3、primary_key = False
  主键,对AutoField设置主键后,就会代替原来的自增 id 列
4、auto_now 和 auto_now_add
  auto_now   自动创建---无论添加或修改,都是当前操作的时间
  auto_now_add  自动创建---永远是创建时的时间
5、choices
GENDER_CHOICE = (
        (u'M', u'Male'),
        (u'F', u'Female'),
    )
gender = models.CharField(max_length=2,choices = GENDER_CHOICE)
6、max_length
7、default  默认值
8、verbose_name  Admin中字段的显示名称
9、name|db_column  数据库中的字段名称
10、unique=True  不允许重复
11、db_index = True  数据库索引
12、editable=True  在Admin里是否可编辑
13、error_messages=None  错误提示
14、auto_created=False  自动创建
15、help_text  在Admin中提示帮助信息
16、validators=[]  自定义规则,对Admin生效
17、upload-to    上传文件,对Admin生效

 

2.连表关系

  • 一对多    models.ForeignKey(类名,[to_field=True][,..])  主键默认关联到对方的主键字段,可以通过主键的 to_field设置关联到的字段。
  • 一对一  models.OneToOneFeild(类名,[to_field=True][,..])   内部实现原理  models.ForeignKey(类名,unique=True)  
  • 多对多    models.ManyToManyFeild(类名,[to_field=True][,..])   
    • 方式:
      • ORM自动创建第三张表
      • 手动创建第三张表,通过through参数 关联

应用场景:

    • 一对一:在某表中创建一行数据时,有一个单选的下拉框(下拉框中的内容被用过一次就消失了)。
      例如:原有含10列数据的一张表保存相关信息,经过一段时间之后,10列无法满足需求,需要为原来的表再添加5列数据。
    • 一对多:当一张表中创建一行数据时,有一个单选的下拉框(可以被重复选择)。
      例如:创建用户信息时候,需要选择一个用户类型【普通用户】【金牌用户】【铂金用户】等。
    • 多对多:在某表中创建一行数据是,有一个可以多选的下拉框。
      例如:创建用户信息,需要为用户指定多个爱好。

3、数据库操作

    • 增加:创建实例,并调用save
    • 更新:a.获取实例,再sava;b.update(指定列)
    • 删除:a. filter().delete(); b.all().delete()
    • 获取:a. 单个=get(id=1) ;b. 所有 = all()
    • 过滤:filter(name='xxx');filter(name__contains='');(id__in = [1,2,3]) ;
      icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)'gt', 'in', 'isnull', 'endswith', 'contains', 'lt', 'startswith', 'iendswith', 'icontains','range', 'istartswith'
    • 排序:order_by("name") =asc ;order_by("-name")=desc
    • 返回第n-m条:第n条[0];前两条[0:2]
    • 指定映射:values
    • 数量:count()
    • 聚合:from django.db.models import Min,Max,Sum objects.all().aggregate(Max('guest_id'))
    • 原始SQL
cursor = connection.cursor()
cursor.execute('''SELECT DISTINCT first_name ROM people_person WHERE last_name = %s""", ['Lennon'])
row = cursor.fetchone()

 

4.操作表

1.基本操作

  增,删,改,查

 #
    #
    # models.Tb1.objects.create(c1='xx', c2='oo')  增加一条数据,可以接受字典类型数据 **kwargs

    # obj = models.Tb1(c1='xx', c2='oo')
    # obj.save()

    #
    #
    # models.Tb1.objects.get(id=123)         # 获取单条数据,不存在则报错(不建议)
    # models.Tb1.objects.all()               # 获取全部
    # models.Tb1.objects.filter(name='seven') # 获取指定条件的数据

    #
    #
    # models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据,没有任何返回值

    #
    # models.Tb1.objects.filter(name='seven').update(gender='0')  # 将指定条件的数据更新,均支持 **kwargs
    # obj = models.Tb1.objects.get(id=1)
    # obj.c1 = '111'
    # obj.save()                                                 # 修改单条数据

2.进阶操作

利用双下划线,将字段和对应的操作连接起来

# 获取个数
    #
    # models.Tb1.objects.filter(name='seven').count()

    # 大于,小于
    #
    # models.Tb1.objects.filter(id__gt=1)              # 获取id大于1的值
    # models.Tb1.objects.filter(id__lt=10)             # 获取id小于10的值
    # models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值

    # in
    #
    # models.Tb1.objects.filter(id__in=[11, 22, 33])   # 获取id等于11、22、33的数据
    # models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in

    # contains
    #
    # models.Tb1.objects.filter(name__contains="ven")
    # models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
    # models.Tb1.objects.exclude(name__icontains="ven")

    # range
    #
    # models.Tb1.objects.filter(id__range=[1, 2])   # 范围bettwen and

    # 其他类似
    #
    # startswith,istartswith, endswith, iendswith,

    # order by
    #
    # models.Tb1.objects.filter(name='seven').order_by('id')    # asc
    # models.Tb1.objects.filter(name='seven').order_by('-id')   # desc

    # limit 、offset
    #
    # models.Tb1.objects.all()[10:20]

    # group by
    from django.db.models import Count, Min, Max, Sum
    # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
    # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
View Code

3.连表操作

利用双下划线和 _set 将表之间的操作连接起来

  • 多对多操作,如果第三张表是自己创建的,不能用 add,set等方法,但可以使用连接查询
from django.db import models

# Create your models here.
class UserType(models.Model):
    nid = models.AutoField(primary_key=True)
    caption = models.CharField(max_length=10)

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)
    user_type = models.ForeignKey(UserType)
    ctime = models.DateTimeField()

class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)


class Group(models.Model):
    gid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    g2h = models.ManyToManyField('Host')




class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)


"""
class Group(models.Model):
    gid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    g2h = models.ManyToManyField('Host', through='HostToGroup')


#手动创建第三张表
class HostToGroup(models.Model):
    gid = models.ForeignKey(Group)
    hid = models.ForeignKey(Host)

    class Meta:
        #左前缀
        #联合索引
        # index_together = ('gid', 'hid')
        # 联合唯一索引
        unique_together = [
            ('hid', 'gid'),
        ]
"""
表结构
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.shortcuts import HttpResponseRedirect
from app01 import models
# Create your views here.
def index(request):
    # 插入
    # models.UserType.objects.create(caption = '管理员')
    # user_dict = {
    #     'username':'yang',
    #     'password':'123456',
    #     'email':'123@163.com',
    #     'user_type_id':'1',
    # }
    # 插入
    # models.UserInfo.objects.create(**user_dict)
    #UserInfo object <class 'app01.models.UserInfo'>
    # ret = models.UserInfo.objects.get(id=1)
    # print(ret,type(ret))

    # __连表查询

    #qurreyset对象 <class 'django.db.models.query.QuerySet'> [{'user_type__caption': '管理员', 'username': 'yang'}, {'user_type__caption': '管理员', 'username': 'yang'}, {'user_type__caption': '管理员', 'username': 'yang'}, {'user_type__caption': '管理员', 'username': 'yang'}]
    # ret = models.UserInfo.objects.all().values('username','user_type__caption')
    # print(type(ret), ret)

    #打印出查询语句
    #SELECT `app01_userinfo`.`username`, `app01_usertype`.`caption` FROM `app01_userinfo` INNER JOIN `app01_usertype` ON (`app01_userinfo`.`user_type_id` = `app01_usertype`.`nid`)
    # print(ret.query)

    #查询 用户类型是管理员的用户
    # ret = models.UserInfo.objects.filter(user_type__caption = '管理员').values('username','user_type__caption')
    # print(ret,type(ret))

    #反向查找 _set
    # obj = models.UserType.objects.filter(caption='管理员').first()
    # print(obj,obj.nid)
    # print(obj.userinfo_set.all())

    #反向查找,把查询选项写到映射中  表名__字段
    # ret = models.UserType.objects.all().values('userinfo__email')
    # print(ret, type(ret))

    #多对多查询
    # for i in range(6):
    #     models.Host.objects.create(hostname='c'+str(i),ip='1.1.1.'+str(i))
    # models.Group.objects.create(name='销售部')
    # models.Group.objects.create(name='市场部')
    # models.Group.objects.create(name='技术部')
    # models.Group.objects.create(name='运营部')
    # models.Group.objects.create(name='客服部')
    # models.Group.objects.create(name='人事部')
    # models.Group.objects.create(name='产品部')
    #将多台机器分配给一组
    # obj = models.Group.objects.get(gid=4)
    # h1 = models.Host.objects.get(hid=1)
    # h2 = models.Host.objects.get(hid=2)
    # 一般方法
    # obj.g2h.add(h1)
    # obj.g2h.add(h2)
    # 优化方法
    # h = models.Host.objects.filter(hid__gt=3)
    # obj.g2h.add(*h)

    #将一台机器分配给多个组
    # h1 = models.Host.objects.get(hid=3)
    # h1.group_set

    # h1.group_set.add(*models.Group.objects.filter(gid__lt=4))

    #多对多删除
    # delete()  本表和第三方表数据都会被删除
    #remove() 这删除本表数据

    #clear()  清空id的自增记录

    return HttpResponse('OK')

 

# F 使用查询条件的值
    #
    # from django.db.models import F
    # models.Tb1.objects.update(num=F('num')+1)

    # Q 构建搜索条件
    from django.db.models import Q
    # con = Q()
    #
    # q1 = Q()
    # q1.connector = 'OR'
    # q1.children.append(('id', 1))
    # q1.children.append(('id', 10))
    # q1.children.append(('id', 9))
    #
    # q2 = Q()
    # q2.connector = 'OR'
    # q2.children.append(('c1', 1))
    # q2.children.append(('c1', 10))
    # q2.children.append(('c1', 9))
    #
    # con.add(q1, 'AND')
    # con.add(q2, 'AND')
    #
    # models.Tb1.objects.filter(con)

    #
    # from django.db import connection
    # cursor = connection.cursor()
    # cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
    # row = cursor.fetchone()
其他

 

posted @ 2016-08-23 15:10  Echo/  阅读(707)  评论(0编辑  收藏  举报