Django之Model组件

Model组件在就已经提到过了,本章介绍更多高级部分。

一、回顾1、定义表(类)
django.db <span style="color: #0000ff;">class user(models.Model): <span style="color: #008000;">#<span style="color: #008000;">数据库表名为app_classname,比如现在这个表存在数据库中为cmdb_user
name=models.CharField(max_length=24) <span style="color: #008000;">#
<span style="color: #008000;">字符串,最大长度24
age=models.IntegerField() <span style="color: #008000;">#<span style="color: #008000;">整数类型

<span style="color: #008000;">#<span style="color: #008000;">#一对多
<span style="color: #0000ff;">from django.db <span style="color: #0000ff;">import<span style="color: #000000;"> models

<span style="color: #0000ff;">class<span style="color: #000000;"> user(models.Model):
name=models.CharField(max_length=24<span style="color: #000000;">)
age=<span style="color: #000000;">models.IntegerField()
user_group=models.ForeignKey(<span style="color: #800000;">'<span style="color: #800000;">usergroup<span style="color: #800000;">',to_field=<span style="color: #800000;">'<span style="color: #800000;">gid<span style="color: #800000;">')<span style="color: #008000;">#<span style="color: #008000;">外键约束,to_field表示关联的字段,生成的字段为user_group_id,不写的话默认和表的主键关联

<span style="color: #0000ff;">class<span style="color: #000000;"> usergroup(models.Model):
gid=models.AutoField(primary_key=<span style="color: #000000;">True)
groupname=models.CharField(max_length=20,unique=<span style="color: #000000;">True)
ctime=models.DateField(auto_now_add=<span style="color: #000000;">True)

<span style="color: #008000;">#<span style="color: #008000;">#一对一
<span style="color: #0000ff;">from django.db <span style="color: #0000ff;">import<span style="color: #000000;"> models

<span style="color: #0000ff;">class<span style="color: #000000;"> user(models.Model):
name=models.CharField(max_length=24<span style="color: #000000;">)
age=<span style="color: #000000;">models.IntegerField()
user_group=models.ForeignKey(<span style="color: #800000;">'<span style="color: #800000;">usergroup<span style="color: #800000;">',to_field=<span style="color: #800000;">'<span style="color: #800000;">gid<span style="color: #800000;">',unique=True)<span style="color: #008000;">#<span style="color: #008000;">加上unique=True确保是一一对应

<span style="color: #0000ff;">class<span style="color: #000000;"> usergroup(models.Model):
gid=models.AutoField(primary_key=<span style="color: #000000;">True)
groupname=models.CharField(max_length=20,unique=<span style="color: #000000;">True)
ctime=models.DateField(auto_now_add=<span style="color: #000000;">True)

<span style="color: #008000;">#<span style="color: #008000;">##多对多<span style="color: #008000;">

<span style="color: #008000;">#########第一种使用传统外键方式关联(自己定义关系)######

<span style="color: #0000ff;">class<span style="color: #000000;"> Host(models.Model):
hid=models.AutoField(primary_key=<span style="color: #000000;">True)
hostname=models.CharField(max_length=20<span style="color: #000000;">)
ip=<span style="color: #000000;">models.GenericIPAddressField()

<span style="color: #0000ff;">class<span style="color: #000000;"> HostGroup(models.Model):
gid=models.AutoField(primary_key=<span style="color: #000000;">True)
groupname=models.CharField(max_length=22<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">自己定义第三张表,可以随意添加字段
<span style="color: #0000ff;">class<span style="color: #000000;"> HostToGroup(models.Model):
hobj=models.ForeignKey(to=<span style="color: #800000;">'<span style="color: #800000;">Host<span style="color: #800000;">',to_field=<span style="color: #800000;">"<span style="color: #800000;">hid<span style="color: #800000;">")<span style="color: #008000;">#<span style="color: #008000;">生成的数据库表字段为hobj_id
gobj=models.ForeignKey(to=<span style="color: #800000;">'<span style="color: #800000;">HostGroup<span style="color: #800000;">',to_field=<span style="color: #800000;">"<span style="color: #800000;">gid<span style="color: #800000;">")<span style="color: #008000;">#<span style="color: #008000;">生成的数据库表字段为gobj_id

<span style="color: #008000;">#<span style="color: #008000;">#########第二种使用django自带的方式创建########
<span style="color: #0000ff;">class<span style="color: #000000;"> Host(models.Model):
hid=models.AutoField(primary_key=<span style="color: #000000;">True)
hostname=models.CharField(max_length=20<span style="color: #000000;">)
ip=<span style="color: #000000;">models.GenericIPAddressField()

<span style="color: #0000ff;">class<span style="color: #000000;"> HostGroup(models.Model):
gid=models.AutoField(primary_key=<span style="color: #000000;">True)
groupname=models.CharField(max_length=22<span style="color: #000000;">)
hobj=models.ManyToManyField(<span style="color: #800000;">'<span style="color: #800000;">Host<span style="color: #800000;">'<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">使用django自带字段创建第三张表,自动关联主键,数据库表名为cmdb_hostgroup_hobj,这种方式不能直接操作第三张表,可以间接操作

<span style="color: #008000;">#<span style="color: #008000;">########第三种自定义第三张表,使用django创建m2m关联字段
<span style="color: #0000ff;">class<span style="color: #000000;"> Host(models.Model):
hid=models.AutoField(primary_key=<span style="color: #000000;">True)
hostname=models.CharField(max_length=20<span style="color: #000000;">)
ip=models.GenericIPAddressField() m=models.ManyToManyField(<span style="color: #800000;">'<span style="color: #800000;">HostGrop<span style="color: #800000;">',through=<span style="color: #800000;">'<span style="color: #800000;">HostToGroup<span style="color: #800000;">',through_fields=[<span style="color: #800000;">'<span style="color: #800000;">hobj<span style="color: #800000;">',<span style="color: #800000;">'<span style="color: #800000;">gobj<span style="color: #800000;">'<span style="color: #000000;">])<span style="color: #008000;">#<span style="color: #008000;">通过自定义m2m关系只能做查询操作

<span style="color: #0000ff;">class<span style="color: #000000;"> HostGroup(models.Model):
gid=models.AutoField(primary_key=<span style="color: #000000;">True)
groupname=models.CharField(max_length=22<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">自己定义第三张表,可以随意添加字段
<span style="color: #0000ff;">class<span style="color: #000000;"> HostToGroup(models.Model):
hobj=models.ForeignKey(to=<span style="color: #800000;">'<span style="color: #800000;">Host<span style="color: #800000;">',to_field=<span style="color: #800000;">"<span style="color: #800000;">gid<span style="color: #800000;">")<span style="color: #008000;">#<span style="color: #008000;">生成的数据库

 2、model字段介绍

3、字段参数

4、元数据自定义

通过自定义元数据可以自定义一些特性

= models.AutoField(primary_key== models.CharField(max_length=32 db_table =
        <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 联合索引,最左前缀模式,当查询字段中的where条件必须从pub_date开头才能匹配到索引</span>
        index_together =<span style="color: #000000;"&gt; [
            (</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;pub_date</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;deadline</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;),]

        
<span style="color: #008000;">#<span style="color: #008000;"> 联合唯一索引
unique_together = ((<span style="color: #800000;">"<span style="color: #800000;">driver<span style="color: #800000;">",<span style="color: #800000;">"<span style="color: #800000;">restaurant<span style="color: #800000;">"<span style="color: #000000;">),)

        </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; admin中显示的表名称</span>

<span style="color: #000000;"> verbose_name

        </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; verbose_name加s</span>
        verbose_name_plural</pre>

 5、多表关系参数

ForeignKey(ForeignObject) to, to_field=None, on_delete=None, ------ </span><span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; func(): </span><span style="color: #0000ff;"&gt;return</span> 10 <span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; MyModel(models.Model): user </span>=<span style="color: #000000;"&gt; models.ForeignKey( to</span>=<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;User</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,to_field</span>=<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;id</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt; on_delete</span>=<span style="color: #000000;"&gt;models.SET(func),) related_name</span>=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()</span> related_query_name=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 反向操作时,使用的连接前缀,用于替换【表名】 如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')</span> limit_choices_to=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 在Admin或ModelForm中显示关联数据时,提供的条件:</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 如:</span> - limit_choices_to={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;nid__gt</span><span style="color: #800000;"&gt;'</span>: 5<span style="color: #000000;"&gt;} </span>- limit_choices_to=<span style="color: #0000ff;"&gt;lambda</span> : {<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;nid__gt</span><span style="color: #800000;"&gt;'</span>: 5<span style="color: #000000;"&gt;} </span><span style="color: #0000ff;"&gt;from</span> django.db.models <span style="color: #0000ff;"&gt;import</span><span style="color: #000000;"&gt; Q </span>- limit_choices_to=Q(nid__gt=10<span style="color: #000000;"&gt;) </span>- limit_choices_to=Q(nid=8) | Q(nid__gt=10<span style="color: #000000;"&gt;) </span>- limit_choices_to=<span style="color: #0000ff;"&gt;lambda</span> : Q(Q(nid=8) | Q(nid__gt=10)) &amp; Q(caption=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;root</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;) db_constraint</span>=True <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 是否在数据库中创建外键约束</span> parent_link=False <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 在Admin中是否显示关联数据</span>

<span style="color: #000000;">

OneToOneField(ForeignKey)
    to,</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 要进行关联的表名</span>
    to_field=None               <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 要关联的表中的字段名称</span>
    on_delete=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 当删除关联表中的数据时,当前表与其关联的行的行为</span>

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

                                        </span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; A(C):
                                            id </span>= models.AutoField(primary_key=<span style="color: #000000;"&gt;True)
                                            code </span>= models.CharField(max_length=1<span style="color: #000000;"&gt;)

ManyToManyField(RelatedField)
    to,</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 要进行关联的表名</span>
    related_name=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 在Admin或ModelForm中显示关联数据时,提供的条件:</span>
                                <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 如:</span>
                                        - limit_choices_to={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;nid__gt</span><span style="color: #800000;"&gt;'</span>: 5<span style="color: #000000;"&gt;}
                                        </span>- limit_choices_to=<span style="color: #0000ff;"&gt;lambda</span> : {<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;nid__gt</span><span style="color: #800000;"&gt;'</span>: 5<span style="color: #000000;"&gt;}

                                        </span><span style="color: #0000ff;"&gt;from</span> django.db.models <span style="color: #0000ff;"&gt;import</span><span style="color: #000000;"&gt; Q
                                        </span>- limit_choices_to=Q(nid__gt=10<span style="color: #000000;"&gt;)
                                        </span>- limit_choices_to=Q(nid=8) | Q(nid__gt=10<span style="color: #000000;"&gt;)
                                        </span>- limit_choices_to=<span style="color: #0000ff;"&gt;lambda</span> : Q(Q(nid=8) | Q(nid__gt=10)) &amp; Q(caption=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;root</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
    symmetrical</span>=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 仅用于多对多自关联时,symmetrical用于指定内部是否创建反向操作的字段</span>
                                <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 做如下操作时,不同的symmetrical会有不同的可选字段</span>

<span style="color: #000000;"> models.BB.objects.filter(...)

                                    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 可选字段有:code,id,m1</span>
                                        <span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; BB(models.Model):

                                        code </span>= models.CharField(max_length=12<span style="color: #000000;"&gt;)
                                        m1 </span>= models.ManyToManyField(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;self</span><span style="color: #800000;"&gt;'</span>,symmetrical=<span style="color: #000000;"&gt;True)

                                    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 可选字段有: bb,code,symmetrical=<span style="color: #000000;"&gt;False)

    through</span>=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 自定义第三张表时,使用字段用于指定关系表</span>
    through_fields=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 自定义第三张表时,使用字段用于指定关系表中那些字段做多对多关系表</span>
                                    <span style="color: #0000ff;"&gt;from</span> django.db <span style="color: #0000ff;"&gt;import</span><span style="color: #000000;"&gt; models

                                    </span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Person(models.Model):
                                        name </span>= models.CharField(max_length=50<span style="color: #000000;"&gt;)

                                    </span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Group(models.Model):
                                        name </span>= models.CharField(max_length=128<span style="color: #000000;"&gt;)
                                        members </span>=<span style="color: #000000;"&gt; models.ManyToManyField(
                                            Person,through</span>=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Membership</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;,through_fields</span>=(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;group</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;person</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;),)

                                    </span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Membership(models.Model):
                                        group </span>= models.ForeignKey(Group,on_delete=<span style="color: #000000;"&gt;models.CASCADE)
                                        person </span>= models.ForeignKey(Person,on_delete=<span style="color: #000000;"&gt;models.CASCADE)
                                        inviter </span>=<span style="color: #000000;"&gt; models.ForeignKey(
                                            Person,on_delete</span>=<span style="color: #000000;"&gt;models.CASCADE,related_name</span>=<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;membership_invites</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,)
                                        invite_reason </span>= models.CharField(max_length=64<span style="color: #000000;"&gt;)
    db_constraint</span>=True,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 是否在数据库中创建外键约束</span>
    db_table=None,<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 默认创建第三张表时,数据库中表的名称</span></pre>

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

<tr>
<td><span style="font-size: 16px;">二、操作</td>
</tr></table>

1.连表正反向查询(反向通过表__set查询)

=models.CharField(max_length=30<span style="color: #0000ff;">class<span style="color: #000000;"> person(models.Model):
username
=models.CharField(max_length=32<span style="color: #000000;">)
pwd
=models.CharField(max_length=32<span style="color: #000000;">)
ut
=models.ForeignKey(to=<span style="color: #800000;">'<span style="color: #800000;">Usertype<span style="color: #800000;">',to_field=<span style="color: #800000;">'<span style="color: #800000;">id<span style="color: #800000;">'<span style="color: #000000;">)

<span style="color: #008000;">#<span style="color: #008000;">##正向查询,通过.的方式
v=<span style="color: #000000;">models.person.objects.all()
<span style="color: #0000ff;">for row <span style="color: #0000ff;">in<span style="color: #000000;"> v:
<span style="color: #0000ff;">print<span style="color: #000000;">(row.username,row.pwd,row.ut.name)

<span style="color: #008000;">#<span style="color: #008000;">##反向查询,默认通过:类名set获取,字段通过:表获取,若设置了关联查询参数(related_name),则改变
v1=<span style="color: #000000;">models.Usertype.objects.all()
<span style="color: #0000ff;">for row1 <span style="color: #0000ff;">in<span style="color: #000000;"> v1:
<span style="color: #0000ff;">print<span style="color: #000000;">(row1.name,row1.id,row1.person_set.all())

models.Usertype.objects.values(<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">',<span style="color: #800000;">'<span style="color: #800000;">person__username<span style="color: #800000;">')

 2、增、删、改、查

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; obj = models.Tb1(c1='xx',c2='oo')</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; obj.save()</span>

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 查</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.get(id=123) # 获取单条数据,不存在则报错(不建议)
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.all() # 获取全部
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(name='seven') # 获取指定条件的数据
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.exclude(name='seven') # 获取指定条件的数据

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 删</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 改</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; models.Tb1.objects.filter(name='seven').update(gender='0')  # 将指定条件的数据更新,均支持 **kwargs</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; obj = models.Tb1.objects.get(id=1)</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; obj.c1 = '111'</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; obj.save()                                                 # 修改单条数据</span></pre>

3、排序、聚合

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 大于,小于</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(idgt=1) # 获取id大于1的值
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(id
gte=1) # 获取id大于等于1的值
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(idlt=10) # 获取id小于10的值
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(id
lte=10) # 获取id小于10的值
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(idlt=10,idgt=1) # 获取id大于1 且 小于10的值

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; in</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(idin=[11,22,33]) # 获取id等于11、22、33的数据
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.exclude(id
in=[11,33]) # not in

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; isnull</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Entry.objects.filter(pub_date__isnull=True)</span>

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; contains</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(namecontains="ven")
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(name
icontains="ven") # icontains大小写不敏感
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.exclude(name__icontains="ven")

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; range</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(id__range=[1,2]) # 范围bettwen and

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 其他类似</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> startswith,istartswith,endswith,iendswith,

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; order by</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(name='seven').order_by('id') # asc
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(name='seven').order_by('-id') # desc

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; group by #当values后面是annotate时候,此时不在时查询,而是分组</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> from django.db.models import Count,Min,Max,Sum
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
<span style="color: #008000;">#<span style="color: #008000;"> SELECT "app01_tb1"."id",COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; limit 、offset</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.all()[10:20]

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; regex正则匹配,iregex 不区分大小写</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.get(titleregex=r'^(An?|The) +')
<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.get(title
iregex=r'^(an?|the) +')

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; date</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_date__date=datetime.date(2005,1,1))
<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_datedategt=datetime.date(2005,1))

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; year</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_date__year=2005)
<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_dateyeargte=2005)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; month</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_date__month=12)
<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_datemonthgte=6)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; day</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_date__day=3)
<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_datedaygte=3)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; week_day</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_dateweek_day=2)
<span style="color: #008000;">#<span style="color: #008000;"> Entry.objects.filter(pub_date
week_day__gte=2)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; hour</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(timestamphour=23)
<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(time
hour=5)
<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(timestamphourgte=12)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; minute</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(timestampminute=29)
<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(time
minute=46)
<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(timestampminutegte=29)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; second</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(timestampsecond=31)
<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(time
second=2)
<span style="color: #008000;">#<span style="color: #008000;"> Event.objects.filter(timestampsecondgte=31)

 4、使用子查询和执行原生SQL

%s"},select_params=(1,)) 2,'name'='wd'],or条件['id'>2 or 'name'='wd'],使用函数['fund(ctime)=1','name'='wd'] %s"},),order_by=['-nid'])#这里还可以使用mysql中的函数
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; F</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> from django.db.models import F
<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.update(num=F('num')+1)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Q</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> 方式一:
<span style="color: #008000;">#<span style="color: #008000;"> Q(nidgt=10)
<span style="color: #008000;">#<span style="color: #008000;"> Q(nid=8) | Q(nid
gt=10)
<span style="color: #008000;">#<span style="color: #008000;"> Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 方式二:</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; con = Q()</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q1 = Q()</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q1.connector = 'OR'</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q1.children.append(('id',1))</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q1.children.append(('id',10))</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q1.children.append(('id',9))</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q2 = Q()</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q2.connector = 'OR'</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q2.children.append(('c1',1))</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q2.children.append(('c1',10))</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; q2.children.append(('c1',9))</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; con.add(q1,'AND')</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; con.add(q2,'AND')</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> models.Tb1.objects.filter(con)

    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 执行原生SQL</span>
    <span style="color: #008000;"&gt;#

<span style="color: #008000;">#<span style="color: #008000;"> from django.db import connection,connections
<span style="color: #008000;">#<span style="color: #008000;"> cursor = connection.cursor() # cursor = connections['default'].cursor()
<span style="color: #008000;">#<span style="color: #008000;"> cursor.execute("""SELECT * from auth_user where id = %s""",[1])
<span style="color: #008000;">#<span style="color: #008000;"> row = cursor.fetchone()

 5、QuerySet对象方法详解

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

<tr>
<td><span style="font-size: 16px;">三、model的验证功能以及内置钩子</td>
</tr></table>

我们知道,model可以用来对数据库进行操作,但是Django中model提供了弱小的验证功能。

1、验证功能:

通过创建对象使用save方法进行操作创建,在对象中使用full_clean()进行验证,使用异常捕捉来进行处理

user_obj=models.user.objects.create(name=,age=22,user_group_id=

2、内置钩子

通过创建对象时,会执行顺序执行full_clean()-->clean_fields()-->clean(),我们可以自定义clean函数进行验证,其中clean_fields方法是字段正则验证

=models.CharField(max_length=24==models.ForeignKey(,null=True,unique=True)
<span style="color: #0000ff;"&gt;def</span> clean(self):   <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;自定义clean验证</span>
    <span style="color: #0000ff;"&gt;from</span> django.core.exceptions <span style="color: #0000ff;"&gt;import</span><span style="color: #000000;"&gt; ValidationError
    c</span>=user.objects.filter(name=<span style="color: #000000;"&gt;self.name).count()
    </span><span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; c:
        </span><span style="color: #0000ff;"&gt;raise</span> ValidationError(message=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;用户名已经存在</span><span style="color: #800000;"&gt;'</span>,code=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;00</span><span style="color: #800000;"&gt;'</span>)  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;由于clean方法捕获ValidationError,所以我们需要抛出该异常才能被捕获到</span>
    </pre>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有需要的朋友自行下载。
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供了身份认证、权限校验、流量管理等。ViewSet在开发接口中不经常用。
一、Django介绍Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。Django 是一个开放源代码的 Web 应用框架,由 Python 写成。Django 遵守 BSD 版权,初次发布于 2005 年 7 月, 并于 2008 年 9 月发布了第一个正式版本 1.0 。Django学习线路Django 采用了 MVT 的软件设计模式,即模型(Model),视图(View)和模板(Template)。这个MVT模式并
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小白快速搭建django项目,并对可能出现的报错进行了分析
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的MysqlDB连接,Python3 支持支持pymysql 所有需要在app里面的__init__加上下面配置:
url: re_path(&#39;authors/$&#39;, views.AuthorView.as_view()), re_path(&#39;book/(?P\d+)/$&#39;, vie
前提 关于html寻找路线: template 如果在各个APP中存在, Django 会优先找全局template 文件下的html文件,如果全局下的template文件没有相关的html Djan
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
from bs4 import BeautifulSoup#kindeditordef kindeditor(request): s = &#39;&#39;&#39; &lt;li&gt;&lt;s
view.py 配置 html 配置
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
浏览器有一个很重要的概念——同源策略(Same-Origin Policy)。所谓同源是指,域名,协议,端口相同。不同源的客户端脚本(javascript、ActionScript)在没明确授权的情况
自动发送 &gt; 依赖jQuery文件 实例--&gt;GET请求: 手动发送 &gt; 依赖浏览器XML对象(也叫原生ajax) Ajax主要就是使用 【XmlHttpRequest】对象来完成请
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render