码迷,mamicode.com
首页 > 其他好文 > 详细

Django-ORM操作

时间:2017-07-03 10:06:38      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:http   连接   exception   class   无符号   唯一索引   查找   cond   unique   

ORM基本增删改查操作:

技术分享
#
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.exclude(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()# 修改单条数据
增删改查

ORM进阶操作:

技术分享
# 获取个数
models.Tb1.objects.filter(name=seven).count()

# 大于,小于
models.Tb1.objects.filter(id__gt=1)              # 获取id大于1的值
models.Tb1.objects.filter(id__gte=1)              # 获取id大于等于1的值
models.Tb1.objects.filter(id__lt=10)             # 获取id小于10的值
models.Tb1.objects.filter(id__lte=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

# isnull
models.Entry.objects.filter(pub_date__isnull=True)

# 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

# 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"

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

# regex正则匹配,iregex 不区分大小写
models.Entry.objects.get(title__regex=r^(An?|The) +)
models.Entry.objects.get(title__iregex=r^(an?|the) +)

# date
import datetime
models.Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
models.Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

# year
models.Entry.objects.filter(pub_date__year=2005)
models.Entry.objects.filter(pub_date__year__gte=2005)

# month
models.Entry.objects.filter(pub_date__month=12)
models.Entry.objects.filter(pub_date__month__gte=6)

# day
models.Entry.objects.filter(pub_date__day=3)
models.Entry.objects.filter(pub_date__day__gte=3)

# week_day
models.Entry.objects.filter(pub_date__week_day=2)
models.Entry.objects.filter(pub_date__week_day__gte=2)

# hour
models.Event.objects.filter(timestamp__hour=23)
models.Event.objects.filter(time__hour=5)
models.Event.objects.filter(timestamp__hour__gte=12)

# minute
models.Event.objects.filter(timestamp__minute=29)
models.Event.objects.filter(time__minute=46)
models.Event.objects.filter(timestamp__minute__gte=29)

# second
models.Event.objects.filter(timestamp__second=31)
models.Event.objects.filter(time__second=2)
models.Event.objects.filter(timestamp__second__gte=31)
进阶操作

ORM高级操作(Q,F,extra,原生SQL)

技术分享
#extra
#extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
models.Entry.objects.extra(select={new_id: "select col from sometable where othercol > %s"}, select_params=(1,))
#select *,(select col from sometable where otherco >1) as new_id from Entry
models.Entry.objects.extra(where=[headline=%s], params=[Lennon])
#select * from Entry where headline=‘Lennon‘
models.Entry.objects.extra(where=["foo=‘a‘ OR bar = ‘a‘", "baz = ‘a‘"])
#select * from Entry where foo=‘a‘ or bar = ‘a‘ and baz=‘a‘
models.Entry.objects.extra(select={new_id: "select id from tb where id > %s"},
                           select_params=(1,), order_by=[-nid])
#select *,(select id from tb where id > 1) from Entry order nid desc

#F
from django.db.models import F
models.Tb1.objects.update(num=F(num)+1)
#先引用(F(‘num‘)+1  用来将原始值取出并+1),再赋值(num=F(‘num‘)+1)相当于,num+1之后更新


#Q
from django.db.models import Q
#方式一:
Q(nid__gt=10)
#where nid > 10
Q(nid=8) | Q(nid__gt=10)
#where nid =8 or nid >10
Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=root)
# where nid = 8 or nid>10 and caption=‘root‘
#方式二:
con = Q()
q1 = Q()
q1.connector = OR
q1.children.append((id, 1))
q1.children.append((id, 10))
q1.children.append((id, 9))
# q1 : where id =1 or id=10 or id=9 
q2 = Q()
q2.connector = OR
q2.children.append((c1, 1))
q2.children.append((c1, 10))
q2.children.append((c1, 9))
#q2 :where c1=1 or c1=10 or c1=9
con.add(q1, AND)
con.add(q2, AND)
#con: where (id =1 or id=10 or id=9 ) and (c1=1 or c1=10 or c1=9)
models.Tb1.objects.filter(con)
#select * from Tb1 where (id =1 or id=10 or id=9 ) and (c1=1 or c1=10 or c1=9)

# 执行原生SQL
from django.db import connection, connections
cursor = connection.cursor()  
#拿到默认数据库default连接的游标
cursors = connections[db1].cursor()
#拿到指定数据库db1的游标
cursor.execute("""SELECT * from auth_user where id = %s""", [1])
row = cursor.fetchone()
ORM高阶操作

ORM其他操作(ORM对象方法拆解)

技术分享
##################################################################
# PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
##################################################################

def all(self)
    # 获取所有的数据对象

def filter(self, *args, **kwargs)
    # 条件查询
    # 条件可以是:参数,字典,Q

def exclude(self, *args, **kwargs)
    # 条件查询
    # 条件可以是:参数,字典,Q

def select_related(self, *fields)
     性能相关:表之间进行join连表操作,一次性获取关联的数据。
     model.tb.objects.all().select_related()
     model.tb.objects.all().select_related(外键字段)
     model.tb.objects.all().select_related(外键字段__外键字段)

def prefetch_related(self, *lookups)
    性能相关:多表连表操作时速度会慢,使用其执行多次SQL查询在Python代码中实现连表操作。
            # 获取所有用户表
            # 获取用户类型表where id in (用户表中的查到的所有用户ID)
            models.UserInfo.objects.prefetch_related(外键字段)



            from django.db.models import Count, Case, When, IntegerField
            Article.objects.annotate(
                numviews=Count(Case(
                    When(readership__what_time__lt=treshold, then=1),
                    output_field=CharField(),
                ))
            )

            students = Student.objects.all().annotate(num_excused_absences=models.Sum(
                models.Case(
                    models.When(absence__type=Excused, then=1),
                default=0,
                output_field=models.IntegerField()
            )))

def annotate(self, *args, **kwargs)
    # 用于实现聚合group by查询

    from django.db.models import Count, Avg, Max, Min, Sum

    v = models.UserInfo.objects.values(u_id).annotate(uid=Count(u_id))
    # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id

    v = models.UserInfo.objects.values(u_id).annotate(uid=Count(u_id)).filter(uid__gt=1)
    # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

    v = models.UserInfo.objects.values(u_id).annotate(uid=Count(u_id,distinct=True)).filter(uid__gt=1)
    # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

def distinct(self, *field_names)
    # 用于distinct去重
    models.UserInfo.objects.values(nid).distinct()
    # select distinct nid from userinfo

    注:只有在PostgreSQL中才能使用distinct进行去重

def order_by(self, *field_names)
    # 用于排序
    models.UserInfo.objects.all().order_by(-id,age)

def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    # 构造额外的查询条件或者映射,如:子查询

    Entry.objects.extra(select={new_id: "select col from sometable where othercol > %s"}, select_params=(1,))
    Entry.objects.extra(where=[headline=%s], params=[Lennon])
    Entry.objects.extra(where=["foo=‘a‘ OR bar = ‘a‘", "baz = ‘a‘"])
    Entry.objects.extra(select={new_id: "select id from tb where id > %s"}, select_params=(1,), order_by=[-nid])

 def reverse(self):
    # 倒序
    models.UserInfo.objects.all().order_by(-nid).reverse()
    # 注:如果存在order_by,reverse则是倒序,如果多个排序则一一倒序


 def defer(self, *fields):
    models.UserInfo.objects.defer(username,id)
    或
    models.UserInfo.objects.filter(...).defer(username,id)
    #映射中排除某列数据

 def only(self, *fields):
    #仅取某个表中的数据
     models.UserInfo.objects.only(username,id)
     或
     models.UserInfo.objects.filter(...).only(username,id)

 def using(self, alias):
     指定使用的数据库,参数为别名(setting中的设置)


##################################################
# PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
##################################################

def raw(self, raw_query, params=None, translations=None, using=None):
    # 执行原生SQL
    models.UserInfo.objects.raw(select * from userinfo)

    # 如果SQL是其他表时,必须将名字设置为当前UserInfo对象的主键列名
    models.UserInfo.objects.raw(select id as nid from 其他表)

    # 为原生SQL设置参数
    models.UserInfo.objects.raw(select id as nid from userinfo where nid>%s, params=[12,])

    # 将获取的到列名转换为指定列名
    name_map = {first: first_name, last: last_name, bd: birth_date, pk: id}
    Person.objects.raw(SELECT * FROM some_other_table, translations=name_map)

    # 指定数据库
    models.UserInfo.objects.raw(select * from userinfo, using="default")

    ################### 原生SQL ###################
    from django.db import connection, connections
    cursor = connection.cursor()  # cursor = connections[‘default‘].cursor()
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone() # fetchall()/fetchmany(..)


def values(self, *fields):
    # 获取每行数据为字典格式

def values_list(self, *fields, **kwargs):
    # 获取每行数据为元祖

def dates(self, field_name, kind, order=ASC):
    # 根据时间进行某一部分进行去重查找并截取指定内容
    # kind只能是:"year"(年), "month"(年-月), "day"(年-月-日)
    # order只能是:"ASC"  "DESC"
    # 并获取转换后的时间
        - year : 年-01-01
        - month: 年-月-01
        - day  : 年-月-日

    models.DatePlus.objects.dates(ctime,day,DESC)

def datetimes(self, field_name, kind, order=ASC, tzinfo=None):
    # 根据时间进行某一部分进行去重查找并截取指定内容,将时间转换为指定时区时间
    # kind只能是 "year", "month", "day", "hour", "minute", "second"
    # order只能是:"ASC"  "DESC"
    # tzinfo时区对象
    models.DDD.objects.datetimes(ctime,hour,tzinfo=pytz.UTC)
    models.DDD.objects.datetimes(ctime,hour,tzinfo=pytz.timezone(Asia/Shanghai))

    """
    pip3 install pytz
    import pytz
    pytz.all_timezones
    pytz.timezone(‘Asia/Shanghai’)
    """

def none(self):
    # 空QuerySet对象


####################################
# METHODS THAT DO DATABASE QUERIES #
####################################

def aggregate(self, *args, **kwargs):
   # 聚合函数,获取字典类型聚合结果
   from django.db.models import Count, Avg, Max, Min, Sum
   result = models.UserInfo.objects.aggregate(k=Count(u_id, distinct=True), n=Count(nid))
   ===> {k: 3, n: 4}

def count(self):
   # 获取个数

def get(self, *args, **kwargs):
   # 获取单个对象

def create(self, **kwargs):
   # 创建对象

def bulk_create(self, objs, batch_size=None):
    # 批量插入
    # batch_size表示一次插入的个数
    objs = [
        models.DDD(name=r11),
        models.DDD(name=r22)
    ]
    models.DDD.objects.bulk_create(objs, 10)

def get_or_create(self, defaults=None, **kwargs):
    # 如果存在,则获取,否则,创建
    # defaults 指定创建时,其他字段的值
    obj, created = models.UserInfo.objects.get_or_create(username=root1, defaults={email: 1111111,u_id: 2, t_id: 2})

def update_or_create(self, defaults=None, **kwargs):
    # 如果存在,则更新,否则,创建
    # defaults 指定创建时或更新时的其他字段
    obj, created = models.UserInfo.objects.update_or_create(username=root1, defaults={email: 1111111,u_id: 2, t_id: 1})

def first(self):
   # 获取第一个

def last(self):
   # 获取最后一个

def in_bulk(self, id_list=None):
   # 根据主键ID进行查找
   id_list = [11,21,31]
   models.DDD.objects.in_bulk(id_list)

def delete(self):
   # 删除

def update(self, **kwargs):
    # 更新

def exists(self):
   # 是否有结果
其他操作

ORM连表查询操作:

技术分享
# 每次循环连表查询
        # restea = models.teac_clas.objects.filter(teachers_id__tName="武沛齐")
        # for i in restea:
        #     print(i.teachers_id.tName)
        #使用values方法直接获取字典无需循环连表
        # restea = models.teac_clas.objects.filter(teachers_id__tName="武沛齐").values("teachers_id__tName")
        # for i in restea:
        #     print(i["teachers_id__tName"])
多对多连表查询

ORM连表示例:

技术分享
class Boy(models.Model):
    bname  = models.CharField(max_length=10)

class Girl(models.Model):
    gname = models.CharField(max_length=10)

class b_g(models.Model):
    b = models.ForeignKey("Boy")
    g = models.ForeignKey("Girl")
    class Mate:
        unique_bj=[("b","g")] #唯一索引(男生和女生只能唯一匹配)
ORM示例数据结构
技术分享
# 编辑者:闫龙
from django.views import View
from django.shortcuts import HttpResponse
from appOne import models

class TestView(View):
    def addData(self):
        girllist=[
            models.Girl(gname="小爽"),
            models.Girl(gname="小红"),
            models.Girl(gname="小黄"),
            models.Girl(gname="小白"),
        ]
        boylist=[
            models.Boy(bname="龙哥"),
            models.Boy(bname="小明"),
            models.Boy(bname="小齐"),
            models.Boy(bname="小杰"),
        ]
        models.Girl.objects.bulk_create(girllist)
        models.Boy.objects.bulk_create(boylist)

    def get(self,request):
        #通过关系表,双下划线到boy中获取名称,在通过双下划线到girl中拿到相应的值
        #res = models.b_g.objects.filter(b_id__bname="龙哥").values("g_id__gname")
        # for i in res:
        #     print(i["g_id__gname"])
        #通过关系表,双下划綫到boy中获取名称,在通过girl对象索引到相应的值
        res = models.b_g.objects.filter(b_id__bname="龙哥")
        for i in res:
            print(i.g.gname)#i.g获取girl对象,拿到相应的名字
        return HttpResponse(".....")
View Code

ORM关系表:

技术分享
from appTwo import models
from django.views import View
from django.shortcuts import HttpResponse
class TestView(View):
    def addData(self):
        girllist=[
            models.girls(gname="小爽"),
            models.girls(gname="小红"),
            models.girls(gname="小黄"),
            models.girls(gname="小白"),
        ]
        boylist=[
            models.boys(bname="龙哥"),
            models.boys(bname="小明"),
            models.boys(bname="小齐"),
            models.boys(bname="小杰"),
        ]
        models.Girl.objects.bulk_create(girllist)
        models.Boy.objects.bulk_create(boylist)

    def get(self,request):
        res = models.boys.objects.filter(bname="龙哥").first()
        girllist = res.bAg.all() #拿到res.id对应在boys_bAg中,对应girl的所有对象
        for i in girllist:
            print(i.gname)
        res.bAg.add(4)
        #向boys_bAg中加入res.id , 4数据等同于insert into boys_bAg(boys_id,girls_id) values(1,4)
        res.bAg.remove(2)
        #删除boys_bAg中boys_id=res.id and girls_id = 2的数据
        res.bAg.set(2)
        #清空boys_bAg中所有boys_id=res.id的数据,并插入数据boys_id=res.id,girls_id=2
        res.bAg.clear()
        #清空boys_bAg中所有boys_id=res.id的数据
        return HttpResponse("......")
ManyToMany

数据库操作

技术分享
数据库操作
        class UserGroup(models.Model):
            """
            部门 3
            """
            title = models.CharField(max_length=32)
        class UserInfo(models.Model):
            """
            员工4
            """
            nid = models.BigAutoField(primary_key=True)
            user = models.CharField(max_length=32)
            password = models.CharField(max_length=64)
            age = models.IntegerField(default=1)
            # ug_id 1
            ug = models.ForeignKey("UserGroup",null=True)
        - 跨表
            正:
                
                1. q = UserInfo.objects.all().first()
                    q.ug.title
                    
                2. 
                    UserInfo.objects.values(nid,ug_id)              
                    UserInfo.objects.values(nid,ug_id,ug__title)  
                
                3. UserInfo.objects.values_list(nid,ug_id,ug__title)
            反:
                1. 小写的表名_set
                    obj = UserGroup.objects.all().first()
                   result = obj.userinfo_set.all() [userinfo对象,userinfo对象,]
                   
                2. 小写的表名
                    v = UserGroup.objects.values(id,title)          
                    v = UserGroup.objects.values(id,title,小写的表名称)          
                    v = UserGroup.objects.values(id,title,小写的表名称__age)          
                    
                3. 小写的表名
                    v = UserGroup.objects.values_list(id,title)          
                    v = UserGroup.objects.values_list(id,title,小写的表名称)          
                    v = UserGroup.objects.values_list(id,title,小写的表名称__age)    

            PS: 前面的所有数据都会显示
            
        - 其他:
            UserInfo.objects.all()
            UserInfo.objects.filter(id=1,id=2)
            UserInfo.objects.all().first()
            UserInfo.objects.all().count()
            UserInfo.objects.all().update()
            UserInfo.objects.all().delete()
            UserInfo.objects.all()[1:19]
            跨表:
                正向:
                    xxxx.filter(ut__title=超级用户).values(id,name,ut__title)
                反向:
                    xxxx.filter(表名称__title=超级用户).values(id,name,表名称__title)
数据库操作

ORM操作补

技术分享
Django ORM操作
            # 1.增删改查
            # 2. 一般:
                # models.UserInfo.objects.filter(id__gt=1)
                # models.UserInfo.objects.filter(id__lt=1)
                # models.UserInfo.objects.filter(id__lte=1)
                # models.UserInfo.objects.filter(id__gte=1)
                # models.UserInfo.objects.filter(id__in=[1,2,3])
                # models.UserInfo.objects.filter(id__range=[1,2])
                # models.UserInfo.objects.filter(name__startswith=‘xxxx‘)
                # models.UserInfo.objects.filter(name__contains=‘xxxx‘)
                # models.UserInfo.objects.exclude(id=1)
            # 3. 排序
                user_list = models.UserInfo.objects.all().order_by(-id,name)
            
            # 4. 分组 annotate ,group by ,加filter相当于having
            
                from django.db.models import Count,Sum,Max,Min
                # v =models.UserInfo.objects.values(‘ut_id‘).annotate(xxxx=Count(‘id‘))
                # print(v.query)
                # v =models.UserInfo.objects.values(‘ut_id‘).annotate(xxxx=Count(‘id‘)).filter(xxxx__gt=2)
                # print(v.query)
                # v =models.UserInfo.objects.filter(id__gt=2).values(‘ut_id‘).annotate(xxxx=Count(‘id‘)).filter(xxxx__gt=2)
                # print(v.query)
                
            
            
            # 5. F,更新时用于获取原来的值
                # from django.db.models import F,Q
                # models.UserInfo.objects.all().update(age=F("age")+1)
            
            # 6. Q,用于构造复杂查询条件
                # 应用一:
                        # models.UserInfo.objects.filter(Q(id__gt=1))
                        # models.UserInfo.objects.filter(Q(id=8) | Q(id=2))
                        # models.UserInfo.objects.filter(Q(id=8) & Q(id=2))
                # 应用二:
                        # q1 = Q()
                        # q1.connector = ‘OR‘
                        # q1.children.append((‘id__gt‘, 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))
                        #
                        # q3 = Q()
                        # q3.connector = ‘AND‘
                        # q3.children.append((‘id‘, 1))
                        # q3.children.append((‘id‘, 2))
                        # q2.add(q3,‘OR‘)
                        #
                        # con = Q()
                        # con.add(q1, ‘AND‘)
                        # con.add(q2, ‘AND‘)
                        
                        # models.UserInfo.objects.filter(con)
            
            # 7. extra, 额外查询条件以及相关表,排序
            
                models.UserInfo.objects.filter(id__gt=1)
                models.UserInfo.objects.all() 
                # id name age ut_id
            
            
                models.UserInfo.objects.extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
                # a. 映射
                    # select 
                    # select_params=None
                    # select 此处 from 表
                
                # b. 条件
                    # where=None
                    # params=None,
                    # select * from 表 where 此处
                
                # c. 表
                    # tables
                    # select * from 表,此处
                    
                # c. 排序
                    # order_by=None
                    # select * from 表 order by 此处
                
                
                models.UserInfo.objects.extra(
                    select={newid:select count(1) from app01_usertype where id>%s},
                    select_params=[1,],
                    where = [age>%s],
                    params=[18,],
                    order_by=[-age],
                    tables=[app01_usertype]
                )
                """
                select 
                    app01_userinfo.id,
                    (select count(1) from app01_usertype where id>1) as newid
                from app01_userinfo,app01_usertype
                where 
                    app01_userinfo.age > 18
                order by 
                    app01_userinfo.age desc
                """
                
                result = models.UserInfo.objects.filter(id__gt=1).extra(
                    where=[app01_userinfo.id < %s],
                    params=[100,],
                    tables=[app01_usertype],
                    order_by=[-app01_userinfo.id],
                    select={uid:1,sw:"select count(1) from app01_userinfo"}
                )
                print(result.query)
                # SELECT (1) AS "uid", (select count(1) from app01_userinfo) AS "sw", "app01_userinfo"."id", "app01_userinfo"."name", "app01_userinfo"."age", "app01_userinfo"."ut_id" FROM "app01_userinfo" , "app01_usertype" WHERE ("app01_userinfo"."id" > 1 AND (app01_userinfo.id < 100)) ORDER BY ("app01_userinfo".id) DESC
            
            # 8. 原生SQL语句
            
                from django.db import connection, connections
                
                cursor = connection.cursor() # connection=default数据
                cursor = connections[db2].cursor()
                
                cursor.execute("""SELECT * from auth_user where id = %s""", [1])
                
                row = cursor.fetchone()
                row = cursor.fetchall()
                
                
                - extra
                - 原生SQL语句
                - raw
                    result = models.UserInfo.objects.raw(select * from userinfo)
                    [obj(UserInfo),obj,]
                    result = models.UserInfo.objects.raw(select id,1 as name,2 as age,4 as ut_id from usertype)
                    [obj(UserInfo),obj,]
                    
                    v1 = models.UserInfo.objects.raw(SELECT id,title FROM app01_usertype,translations=name_map)
                    
            # 9. 简单的操作
                http://www.cnblogs.com/wupeiqi/articles/6216618.html
View Code

 Model

技术分享
AutoField(Field)
        - int自增列,必须填入参数 primary_key=True

    BigAutoField(AutoField)
        - bigint自增列,必须填入参数 primary_key=True

        注:当model中如果没有自增列,则自动会创建一个列名为id的列
        from django.db import models

        class UserInfo(models.Model):
            # 自动创建一个列名为id的且为自增的整数列
            username = models.CharField(max_length=32)

        class Group(models.Model):
            # 自定义自增列
            nid = models.AutoField(primary_key=True)
            name = models.CharField(max_length=32)

    SmallIntegerField(IntegerField):
        - 小整数 -32768 ~ 32767

    PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - 正小整数 0 ~ 32767
    IntegerField(Field)
        - 整数列(有符号的) -2147483648 ~ 2147483647

    PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - 正整数 0 ~ 2147483647

    BigIntegerField(IntegerField):
        - 长整型(有符号的) -9223372036854775808 ~ 9223372036854775807

    BooleanField(Field)
        - 布尔值类型

    NullBooleanField(Field):
        - 可以为空的布尔值

    CharField(Field)
        - 字符类型
        - 必须提供max_length参数, max_length表示字符长度

    TextField(Field)
        - 文本类型

    EmailField(CharField):
        - 字符串类型,Django Admin以及ModelForm中提供验证机制

    IPAddressField(Field)
        - 字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制

    GenericIPAddressField(Field)
        - 字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6
        - 参数:
            protocol,用于指定Ipv4或Ipv6, both,"ipv4","ipv6"
            unpack_ipv4, 如果指定为True,则输入::ffff:192.0.2.1时候,可解析为192.0.2.1,开启刺功能,需要protocol="both"

    URLField(CharField)
        - 字符串类型,Django Admin以及ModelForm中提供验证 URL

    SlugField(CharField)
        - 字符串类型,Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符(减号)

    CommaSeparatedIntegerField(CharField)
        - 字符串类型,格式必须为逗号分割的数字

    UUIDField(Field)
        - 字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证

    FilePathField(Field)
        - 字符串,Django Admin以及ModelForm中提供读取文件夹下文件的功能
        - 参数:
                path,                      文件夹路径
                match=None,                正则匹配
                recursive=False,           递归下面的文件夹
                allow_files=True,          允许文件
                allow_folders=False,       允许文件夹

    FileField(Field)
        - 字符串,路径保存在数据库,文件上传到指定目录
        - 参数:
            upload_to = ""      上传文件的保存路径
            storage = None      存储组件,默认django.core.files.storage.FileSystemStorage

    ImageField(FileField)
        - 字符串,路径保存在数据库,文件上传到指定目录
        - 参数:
            upload_to = ""      上传文件的保存路径
            storage = None      存储组件,默认django.core.files.storage.FileSystemStorage
            width_field=None,   上传图片的高度保存的数据库字段名(字符串)
            height_field=None   上传图片的宽度保存的数据库字段名(字符串)

    DateTimeField(DateField)
        - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

    DateField(DateTimeCheckMixin, Field)
        - 日期格式      YYYY-MM-DD

    TimeField(DateTimeCheckMixin, Field)
        - 时间格式      HH:MM[:ss[.uuuuuu]]

    DurationField(Field)
        - 长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型

    FloatField(Field)
        - 浮点型

    DecimalField(Field)
        - 10进制小数
        - 参数:
            max_digits,小数总长度
            decimal_places,小数位长度

    BinaryField(Field)
        - 二进制类型
字段列表
技术分享
class UnsignedIntegerField(models.IntegerField):
    def db_type(self, connection):
        return integer UNSIGNED

PS: 返回值为字段在数据库中的属性,Django字段默认的值为:
    AutoField: integer AUTO_INCREMENT,
    BigAutoField: bigint AUTO_INCREMENT,
    BinaryField: longblob,
    BooleanField: bool,
    CharField: varchar(%(max_length)s),
    CommaSeparatedIntegerField: varchar(%(max_length)s),
    DateField: date,
    DateTimeField: datetime,
    DecimalField: numeric(%(max_digits)s, %(decimal_places)s),
    DurationField: bigint,
    FileField: varchar(%(max_length)s),
    FilePathField: varchar(%(max_length)s),
    FloatField: double precision,
    IntegerField: integer,
    BigIntegerField: bigint,
    IPAddressField: char(15),
    GenericIPAddressField: char(39),
    NullBooleanField: bool,
    OneToOneField: integer,
    PositiveIntegerField: integer UNSIGNED,
    PositiveSmallIntegerField: smallint UNSIGNED,
    SlugField: varchar(%(max_length)s),
    SmallIntegerField: smallint,
    TextField: longtext,
    TimeField: time,
    UUIDField: char(32),
自定义无符号整数字段
技术分享
1.触发Model中的验证和错误提示有两种方式:
        a. Django Admin中的错误信息会优先根据Admiin内部的ModelForm错误信息提示,如果都成功,才来检查Model的字段并显示指定错误信息
        b. 使用ModelForm
        c. 调用Model对象的 clean_fields 方法,如:
            # models.py
            class UserInfo(models.Model):
                nid = models.AutoField(primary_key=True)
                username = models.CharField(max_length=32)

                email = models.EmailField(error_messages={invalid: 格式错了.})

            # views.py
            def index(request):
                obj = models.UserInfo(username=11234, email=uu)
                try:
                    print(obj.clean_fields())
                except Exception as e:
                    print(e)
                return HttpResponse(ok)

           # Model的clean方法是一个钩子,可用于定制操作,如:上述的异常处理。

    2.Admin中修改错误提示
        # admin.py
        from django.contrib import admin
        from model_club import models
        from django import forms


        class UserInfoForm(forms.ModelForm):
            age = forms.IntegerField(initial=1, error_messages={required: 请输入数值., invalid: 年龄必须为数值.})

            class Meta:
                model = models.UserInfo
                # fields = (‘username‘,)
                fields = "__all__"
                exclude = [title]
                labels = { name:Writer, }
                help_texts = {name:some useful help text.,}
                error_messages={ name:{max_length:"this writer name is too long"} }
                widgets={name:Textarea(attrs={cols:80,rows:20})}

        class UserInfoAdmin(admin.ModelAdmin):
            form = UserInfoForm

        admin.site.register(models.UserInfo, UserInfoAdmin)
attention
技术分享
null                数据库中字段是否可以为空
    db_column           数据库中字段的列名
    default             数据库中字段的默认值
    primary_key         数据库中字段是否为主键
    db_index            数据库中字段是否可以建立索引
    unique              数据库中字段是否可以建立唯一索引
    unique_for_date     数据库中字段【日期】部分是否可以建立唯一索引
    unique_for_month    数据库中字段【月】部分是否可以建立唯一索引
    unique_for_year     数据库中字段【年】部分是否可以建立唯一索引

    verbose_name        Admin中显示的字段名称
    blank               Admin中是否允许用户输入为空
    editable            Admin中是否可以编辑
    help_text           Admin中该字段的提示信息
    choices             Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
                        如:gf = models.IntegerField(choices=[(0, 何穗),(1, 大表姐),],default=1)

    error_messages      自定义错误信息(字典类型),从而定制想要显示的错误信息;
                        字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
                        如:{null: "不能为空.", invalid: 格式错误}

    validators          自定义错误验证(列表类型),从而定制想要的验证规则
                        from django.core.validators import RegexValidator
                        from django.core.validators import EmailValidator,URLValidator,DecimalValidator,                        MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                        如:
                            test = models.CharField(
                                max_length=32,
                                error_messages={
                                    c1: 优先错信息1,
                                    c2: 优先错信息2,
                                    c3: 优先错信息3,
                                },
                                validators=[
                                    RegexValidator(regex=root_\d+, message=错误了, code=c1),
                                    RegexValidator(regex=root_112233\d+, message=又错误了, code=c2),
                                    EmailValidator(message=又错误了, code=c3), ]
                            )
字段参数
技术分享
class UserInfo(models.Model):
        nid = models.AutoField(primary_key=True)
        username = models.CharField(max_length=32)
        class Meta:
            # 数据库中生成的表名称 默认 app名称 + 下划线 + 类名
            db_table = "table_name"

            # 联合索引
            index_together = [
                ("pub_date", "deadline"),
            ]

            # 联合唯一索引
            unique_together = (("driver", "restaurant"),)

            # admin中显示的表名称
            verbose_name

            # verbose_name加s
            verbose_name_plural
元信息
技术分享
ForeignKey(ForeignObject) # ForeignObject(RelatedField)
        to,                         # 要进行关联的表名
        to_field=None,              # 要关联的表中的字段名称
        on_delete=None,             # 当删除关联表中的数据时,当前表与其关联的行的行为
                                        - models.CASCADE,删除关联数据,与之关联也删除
                                        - models.DO_NOTHING,删除关联数据,引发错误IntegrityError
                                        - models.PROTECT,删除关联数据,引发错误ProtectedError
                                        - models.SET_NULL,删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空)
                                        - models.SET_DEFAULT,删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值)
                                        - models.SET,删除关联数据,
                                                      a. 与之关联的值设置为指定值,设置:models.SET(值)
                                                      b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

                                                        def func():
                                                            return 10

                                                        class MyModel(models.Model):
                                                            user = models.ForeignKey(
                                                                to="User",
                                                                to_field="id"
                                                                on_delete=models.SET(func),)
        related_name=None,          # 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
        related_query_name=None,    # 反向操作时,使用的连接前缀,用于替换【表名】     如: models.UserGroup.objects.filter(表名__字段名=1).values(‘表名__字段名‘)
        limit_choices_to=None,      # 在Admin或ModelForm中显示关联数据时,提供的条件:
                                    # 如:
                                            - limit_choices_to={nid__gt: 5}
                                            - limit_choices_to=lambda : {nid__gt: 5}

                                            from django.db.models import Q
                                            - limit_choices_to=Q(nid__gt=10)
                                            - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
                                            - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=root)
        db_constraint=True          # 是否在数据库中创建外键约束
        parent_link=False           # 在Admin中是否显示关联数据


    OneToOneField(ForeignKey)
        to,                         # 要进行关联的表名
        to_field=None               # 要关联的表中的字段名称
        on_delete=None,             # 当删除关联表中的数据时,当前表与其关联的行的行为

                                    ###### 对于一对一 ######
                                    # 1. 一对一其实就是 一对多 + 唯一索引
                                    # 2.当两个类之间有继承关系时,默认会创建一个一对一字段
                                    # 如下会在A表中额外增加一个c_ptr_id列且唯一:
                                            class C(models.Model):
                                                nid = models.AutoField(primary_key=True)
                                                part = models.CharField(max_length=12)

                                            class A(C):
                                                id = models.AutoField(primary_key=True)
                                                code = models.CharField(max_length=1)

    ManyToManyField(RelatedField)
        to,                         # 要进行关联的表名
        related_name=None,          # 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
        related_query_name=None,    # 反向操作时,使用的连接前缀,用于替换【表名】     如: models.UserGroup.objects.filter(表名__字段名=1).values(‘表名__字段名‘)
        limit_choices_to=None,      # 在Admin或ModelForm中显示关联数据时,提供的条件:
                                    # 如:
                                            - limit_choices_to={nid__gt: 5}
                                            - limit_choices_to=lambda : {nid__gt: 5}

                                            from django.db.models import Q
                                            - limit_choices_to=Q(nid__gt=10)
                                            - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
                                            - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=root)
        symmetrical=None,           # 仅用于多对多自关联时,symmetrical用于指定内部是否创建反向操作的字段
                                    # 做如下操作时,不同的symmetrical会有不同的可选字段
                                        models.BB.objects.filter(...)

                                        # 可选字段有:code, id, m1
                                            class BB(models.Model):

                                            code = models.CharField(max_length=12)
                                            m1 = models.ManyToManyField(self,symmetrical=True)

                                        # 可选字段有: bb, code, id, m1
                                            class BB(models.Model):

                                            code = models.CharField(max_length=12)
                                            m1 = models.ManyToManyField(self,symmetrical=False)

        through=None,               # 自定义第三张表时,使用字段用于指定关系表
        through_fields=None,        # 自定义第三张表时,使用字段用于指定关系表中那些字段做多对多关系表
                                        from django.db import models

                                        class Person(models.Model):
                                            name = models.CharField(max_length=50)

                                        class Group(models.Model):
                                            name = models.CharField(max_length=128)
                                            members = models.ManyToManyField(
                                                Person,
                                                through=Membership,
                                                through_fields=(group, person),
                                            )

                                        class Membership(models.Model):
                                            group = models.ForeignKey(Group, on_delete=models.CASCADE)
                                            person = models.ForeignKey(Person, on_delete=models.CASCADE)
                                            inviter = models.ForeignKey(
                                                Person,
                                                on_delete=models.CASCADE,
                                                related_name="membership_invites",
                                            )
                                            invite_reason = models.CharField(max_length=64)
        db_constraint=True,         # 是否在数据库中创建外键约束
        db_table=None,              # 默认创建第三张表时,数据库中表的名称
多表关系及参数

 

Django-ORM操作

标签:http   连接   exception   class   无符号   唯一索引   查找   cond   unique   

原文地址:http://www.cnblogs.com/fortunate/p/7109345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!