微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django:Django中的ORM

一、Django项目使用MysqL数据库

1,在Django项目的settings.py,文件中,配置数据库连接信息:

DATABASES =: MysqL: 数据库名称,数据库 : 数据库用户名: 数据库密码: 数据库IP: 3306

2,在Django项目中__init__.py文件中写如下代码,告诉Django使用pyMysqL模块连接MysqL数据库

MysqL

pyMysqL.installasMysqLdb()

二,Model

在Django中model是你数据的单一、明确的信息来源。它包含了你存储的数据的重要字段和行为。通常,一个模型(model)映射到一个数据库表,

基本情况:

三,快速入门

下面这个例子定义了一个 Person 模型,包含 first_name 和 last_name

from django.db import models

class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)

first_name 和 last_name 是模型的字段。每个字段被指定为一个属性,每个属性映射到一个数据库列。

上面的 Person 模型将会像这样创建一个数据库表:

CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY,"first_name" varchar(30) NOT NULL,"last_name" varchar(30) NOT NULL );

一些说明:

  • 表myapp_person的名称自动生成的,如果你要自定义表名,需要在model的Meta类中指定 db_table 参数,强烈建议使用小写表名,特别是使用MysqL作为后端数据库时。
  • id字段是自动添加的,如果你想要指定自定义主键,只需在其中一个字段中指定 primary_key=True 即可。如果Django发现你已经明确地设置了Field.primary_key,它将不会添加自动ID列。
  • 本示例中的CREATE TABLE sql使用Postgresql语法进行格式化,但值得注意的是,Django会根据配置文件中指定的数据库后端类型来生成相应的sql语句。
  • Django支持MysqL5.5及更高版本。

四,字段

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
- int自增列,必须填入参数 primary_key=BigAutoField(AutoField) </span>- bigint自增列,必须填入参数 primary_key=<span style="color: #000000"&gt;True 注:当model中如果没有自增列,则<a href="/tag/zidong/" target="_blank" class="keywords">自动</a>会创建<a href="/tag/yige/" target="_blank" class="keywords">一个</a>列名为id的列 </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; UserInfo(models.Model): </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; <a href="/tag/zidong/" target="_blank" class="keywords">自动</a>创建<a href="/tag/yige/" target="_blank" class="keywords">一个</a>列名为id的且为自增的整数列</span> username = models.CharField(max_length=32<span style="color: #000000"&gt;) </span><span style="color: #0000ff"&gt;class</span><span style="color: #000000"&gt; Group(models.Model): </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; <a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a>自增列</span> nid = models.AutoField(primary_key=<span style="color: #000000"&gt;True) name </span>= models.CharField(max_length=32<span style="color: #000000"&gt;) SmallIntegerField(IntegerField): </span>- 小整数 -32768 ~ 32767<span style="color: #000000"&gt; PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin,IntegerField) </span>- 正小整数 0 ~ 32767<span style="color: #000000"&gt; IntegerField(Field) </span>- 整数列(有符号的) -2147483648 ~ 2147483647<span style="color: #000000"&gt; PositiveIntegerField(PositiveIntegerRelDbTypeMixin,IntegerField) </span>- 正整数 0 ~ 2147483647<span style="color: #000000"&gt; BigIntegerField(IntegerField): </span>- 长整型(有符号的) -9223372036854775808 ~ 9223372036854775807<span style="color: #000000"&gt; BooleanField(Field) </span>-<span style="color: #000000"&gt; 布尔值类型 NullBooleanField(Field): </span>-<span style="color: #000000"&gt; 可以为空的布尔值 CharField(Field) </span>-<span style="color: #000000"&gt; 字符类型 </span>-<span style="color: #000000"&gt; 必须提供max_length参数, max_length表示字符长度 TextField(Field) </span>-<span style="color: #000000"&gt; 文本类型 EmailField(CharField): </span>-<span style="color: #000000"&gt; 字符串类型,Django Admin以及ModelForm中提供验证机制 IPAddressField(Field) </span>-<span style="color: #000000"&gt; 字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制 GenericIPAddressField(Field) </span>-<span style="color: #000000"&gt; 字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6 </span>-<span style="color: #000000"&gt; 参数: protocol,用于指定Ipv4或Ipv6, </span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;both</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;ipv4</span><span style="color: #800000"&gt;"</span>,<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;ipv6</span><span style="color: #800000"&gt;"</span><span style="color: #000000"&gt; unpack_ipv4, 如果指定为True,则输入::ffff:</span>192.0.2.1时候,可解析为192.0.2.1,开启此<a href="/tag/gongneng/" target="_blank" class="keywords">功能</a>,需要protocol=<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;both</span><span style="color: #800000"&gt;"</span><span style="color: #000000"&gt; URLField(CharField) </span>-<span style="color: #000000"&gt; 字符串类型,Django Admin以及ModelForm中提供验证 URL SlugField(CharField) </span>-<span style="color: #000000"&gt; 字符串类型,Django Admin以及ModelForm中提供验证<a href="/tag/zhichi/" target="_blank" class="keywords">支持</a> 字母、数字、下划线、连接符(减号) CommaSep<a href="/tag/ara/" target="_blank" class="keywords">ara</a>tedIntegerField(CharField) </span>-<span style="color: #000000"&gt; 字符串类型,格式必须为逗号分割的数字 UUIDField(Field) </span>-<span style="color: #000000"&gt; 字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证 FilePathField(Field) </span>-<span style="color: #000000"&gt; 字符串,Django Admin以及ModelForm中提供读取<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>夹下<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>的<a href="/tag/gongneng/" target="_blank" class="keywords">功能</a> </span>-<span style="color: #000000"&gt; 参数: path,<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>夹路径 match</span>=<span style="color: #000000"&gt;None,正则匹配 recursive</span>=<span style="color: #000000"&gt;False,递归下面的<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>夹 allow_files</span>=<span style="color: #000000"&gt;True,允许<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a> allow_folders</span>=<span style="color: #000000"&gt;False,允许<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>夹 FileField(Field) </span>-<span style="color: #000000"&gt; 字符串,路径保存在<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>,<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a><a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a>到指定目录 </span>-<span style="color: #000000"&gt; 参数: upload_to </span>= <span style="color: #800000"&gt;""</span><span style="color: #000000"&gt; <a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>的保存路径 storage </span>=<span style="color: #000000"&gt; None 存储组件,<a href="/tag/mo/" target="_blank" class="keywords">默</a>认django.core.files.storage.FileSy<a href="/tag/stem/" target="_blank" class="keywords">stem</a>Storage ImageField(FileField) </span>-<span style="color: #000000"&gt; 字符串,路径保存在<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>,<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a><a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a>到指定目录 </span>-<span style="color: #000000"&gt; 参数: upload_to </span>= <span style="color: #800000"&gt;""</span><span style="color: #000000"&gt; <a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>的保存路径 storage </span>=<span style="color: #000000"&gt; None 存储组件,<a href="/tag/mo/" target="_blank" class="keywords">默</a>认django.core.files.storage.FileSy<a href="/tag/stem/" target="_blank" class="keywords">stem</a>Storage width_field</span>=<span style="color: #000000"&gt;None,<a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/tupian/" target="_blank" class="keywords">图片</a>的高度保存的<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>字段名(字符串) height_field</span>=<span style="color: #000000"&gt;None <a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/tupian/" target="_blank" class="keywords">图片</a>的宽度保存的<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>字段名(字符串) DateTimeField(DateField) </span>- 日期+时间格式 YYYY-MM-<span style="color: #000000"&gt;DD HH:MM[:ss[.uuuuuu]][TZ] DateField(DateTimeCheckMixin,Field) </span>- 日期格式 YYYY-MM-<span style="color: #000000"&gt;DD TimeField(DateTimeCheckMixin,Field) </span>-<span style="color: #000000"&gt; 时间格式 HH:MM[:ss[.uuuuuu]] DurationField(Field) </span>-<span style="color: #000000"&gt; <a href="/tag/changzhengshu/" target="_blank" class="keywords">长整数</a>,时间间隔,<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>中按照bigint存储,ORM中<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>的值为datetime.<a href="/tag/timedelta/" target="_blank" class="keywords">timedelta</a>类型 FloatField(Field) </span>-<span style="color: #000000"&gt; 浮点型 DecimalField(Field) </span>-<span style="color: #000000"&gt; 10进制小数 </span>-<span style="color: #000000"&gt; 参数: max_digits,小数总长度 decimal_places,小数位长度 BinaryField(Field) </span>-<span style="color: #000000"&gt; 二进制类型

字段相关内容

1,常用字段

  1)AutoField

  int自增列,必须填入参数 primary_key=True。当model中如果没有自增列,则自动会创建一个列名为id的列。

  2)IntegerField

  一个整数类型,范围在 -2147483648 to 2147483647

  3)CharField

  字符类型,必须提供max_length参数, max_length表示字符长度。

  4)DateField

  日期字段,日期格式  YYYY-MM-DD,相当于Python中的datetime.date()实例

  5)DateTimeField

  日期时间字段,格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ],相当于Python中的datetime.datetime()实例。

五,自定义字段

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
自定义的char类型的字段类 __init__(self,max_length,*args,**kwargs): self.max_length =__init__(max_length=max_length,**kwargs)
</span><span style="color: #0000ff"&gt;def</span><span style="color: #000000"&gt; db_type(self,connection):
    </span><span style="color: #800000"&gt;"""</span><span style="color: #800000"&gt;
    限定<a href="/tag/shengcheng/" target="_blank" class="keywords">生成</a><a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>表的字段类型为char,长度为max_length指定的值
    </span><span style="color: #800000"&gt;"""</span>
    <span style="color: #0000ff"&gt;return</span> <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;char(<a href="/tag/s/" target="_blank" class="keywords">%s</a>)</span><span style="color: #800000"&gt;'</span> %<span style="color: #000000"&gt; self.max_length

<span style="color: #0000ff">class<span style="color: #000000"> Class(models.Model):
id = models.AutoField(primary_key=<span style="color: #000000">True)
title = models.CharField(max_length=25<span style="color: #000000">)
<span style="color: #008000">#<span style="color: #008000"> 使用自定义的char类型的字段
cname = FixedCharField(max_length=25)

自定义字段

六,注意事项

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
1错误提示有两种方式: a. Django Admin中的错误信息会优先根据Admiin内部的ModelForm错误信息提示,如果都成功,才来检查Model的字段并显示指定错误信息 b. 使用ModelForm c. 调用Model对象的 clean_fields 方法,如: = models.AutoField(primary_key== models.CharField(max_length=32 email </span>= models.EmailField(error_messages={<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;invalid</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;格式错了.</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;}) </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; views.py</span> <span style="color: #0000ff"&gt;def</span><span style="color: #000000"&gt; index(request): obj </span>= models.UserInfo(username=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;11234</span><span style="color: #800000"&gt;'</span>,email=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;uu</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;) </span><span style="color: #0000ff"&gt;try</span><span style="color: #000000"&gt;: </span><span style="color: #0000ff"&gt;print</span><span style="color: #000000"&gt;(obj.clean_fields()) </span><span style="color: #0000ff"&gt;except</span><span style="color: #000000"&gt; Exception as e: </span><span style="color: #0000ff"&gt;print</span><span style="color: #000000"&gt;(e) </span><span style="color: #0000ff"&gt;return</span> HttpResponse(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;ok</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;) </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; Model的clean<a href="/tag/fangfa/" target="_blank" class="keywords">方法</a>是<a href="/tag/yige/" target="_blank" class="keywords">一个</a>钩子,可用于定制操作,如:上述的异常处理。</span> 2<span style="color: #000000"&gt;.Admin中<a href="/tag/xiugai/" target="_blank" class="keywords">修改</a><a href="/tag/cuowu/" target="_blank" class="keywords">错误</a><a href="/tag/tishi/" target="_blank" class="keywords">提示</a> </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; admin.py</span> <span style="color: #0000ff"&gt;from</span> django.contrib <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; admin </span><span style="color: #0000ff"&gt;from</span> model_club <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; models </span><span style="color: #0000ff"&gt;from</span> django <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; forms </span><span style="color: #0000ff"&gt;class</span><span style="color: #000000"&gt; UserInfoForm(forms.ModelForm): age </span>= forms.IntegerField(initial=1,error_messages={<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;<a href="/tag/required/" target="_blank" class="keywords">required</a></span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;请输入数值.</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;invalid</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;年龄必须为数值.</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; <a href="/tag/Meta/" target="_blank" class="keywords">Meta</a>: model </span>=<span style="color: #000000"&gt; models.UserInfo </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; fields = ('username',)</span> fields = <span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;__all__</span><span style="color: #800000"&gt;"</span><span style="color: #000000"&gt; exclude </span>= [<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;title</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;] labels </span>= { <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;name</span><span style="color: #800000"&gt;'</span>:<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;Writer</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;,} help_texts </span>= {<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;name</span><span style="color: #800000"&gt;'</span>:<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;some useful help text.</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;,} error_messages</span>={ <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;name</span><span style="color: #800000"&gt;'</span>:{<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;max_length</span><span style="color: #800000"&gt;'</span>:<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;this writer name is too long</span><span style="color: #800000"&gt;"</span><span style="color: #000000"&gt;} } widgets</span>={<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;name</span><span style="color: #800000"&gt;'</span>:Textarea(attrs={<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;cols</span><span style="color: #800000"&gt;'</span>:80,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;rows</span><span style="color: #800000"&gt;'</span>:20<span style="color: #000000"&gt;})} </span><span style="color: #0000ff"&gt;class</span><span style="color: #000000"&gt; UserInfoAdmin(admin.ModelAdmin): form </span>=<span style="color: #000000"&gt; UserInfoForm admin.site.register(models.UserInfo,UserInfoAdmin)

注意事项

七,字段参数

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
数据库中字段是否可以为空 db_column 数据库中字段的列名 default 数据库中字段的认值 primary_key 数据库中字段是否为主键 db_index 数据库中字段是否可以建立索引 unique 数据库中字段是否可以建立唯一索引 unique_for_date 数据库中字段【日期】部分是否可以建立唯一索引 unique_for_month 数据库中字段【月】部分是否可以建立唯一索引 unique_for_year 数据库中字段【年】部分是否可以建立唯一索引
verbose_name        Admin中<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>的字段<a href="/tag/mingcheng/" target="_blank" class="keywords">名称</a>
blank               Admin中是否允许<a href="/tag/yonghu/" target="_blank" class="keywords">用户</a>输入为空
editable            Admin中是否可以编辑
help_text           Admin中该字段的<a href="/tag/tishi/" target="_blank" class="keywords">提示</a>信息
choices             Admin中<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>选择框的<a href="/tag/neirong/" target="_blank" class="keywords">内容</a>,用不变动的数据放在内存中从而避免跨表操作
                    如:gf </span>= models.IntegerField(choices=[(0,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;何穗</span><span style="color: #800000"&gt;'</span>),(1,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;大表姐</span><span style="color: #800000"&gt;'</span>),],default=1<span style="color: #000000"&gt;)

error_messages      <a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/cuowu/" target="_blank" class="keywords">错误</a>信息(字典类型),从而定制想要<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>的<a href="/tag/cuowu/" target="_blank" class="keywords">错误</a>信息;
                    字典健:null,blank,invalid,invalid_choice,unique,</span><span style="color: #0000ff"&gt;and</span><span style="color: #000000"&gt; unique_for_date
                    如:{</span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;null</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;不能为空.</span><span style="color: #800000"&gt;"</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;invalid</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;格式<a href="/tag/cuowu/" target="_blank" class="keywords">错误</a></span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;}

validators          <a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/cuowu/" target="_blank" class="keywords">错误</a>验证(列表类型),从而定制想要的验证规则
                    </span><span style="color: #0000ff"&gt;from</span> django.core.validators <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; RegexValidator
                    </span><span style="color: #0000ff"&gt;from</span> django.core.validators <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; EmailValidator,URLValidator,DecimalValidator,\
                    MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                    如:
                        test </span>=<span style="color: #000000"&gt; models.CharField(
                            max_length</span>=32<span style="color: #000000"&gt;,error_messages</span>=<span style="color: #000000"&gt;{
                                </span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;c1</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;优先错信息1</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;,</span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;c2</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;优先错信息2</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;,</span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;c3</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;优先错信息3</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;,},validators</span>=<span style="color: #000000"&gt;[
                                RegexValidator(regex</span>=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;root_\d+</span><span style="color: #800000"&gt;'</span>,message=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;<a href="/tag/cuowu/" target="_blank" class="keywords">错误</a>了</span><span style="color: #800000"&gt;'</span>,code=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;c1</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;),RegexValidator(regex</span>=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;root_112233\d+</span><span style="color: #800000"&gt;'</span>,message=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;又<a href="/tag/cuowu/" target="_blank" class="keywords">错误</a>了</span><span style="color: #800000"&gt;'</span>,code=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;c2</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;),EmailValidator(message</span>=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;又<a href="/tag/cuowu/" target="_blank" class="keywords">错误</a>了</span><span style="color: #800000"&gt;'</span>,code=<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;c3</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;),]
                        )

字段参数

八,元信息

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
= models.AutoField(primary_key== models.CharField(max_length=32Meta: 数据库中生成的表名称 认 app名称 + 下划线 + 类名 db_table =
        <span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 联合索引</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><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 联合唯一索引</span>
        unique_together = ((<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;driver</span><span style="color: #800000"&gt;"</span>,<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;restaurant</span><span style="color: #800000"&gt;"</span><span style="color: #000000"&gt;),)

        </span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; admin中<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>的表<a href="/tag/mingcheng/" target="_blank" class="keywords">名称</a></span>

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

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

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

元信息

九,多表关系和参数

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
ForeignKey(ForeignObject) to, to_field=None,名称 on_delete=None,删除关联表中的数据时,当前表与其关联的行的行为 -删除关联数据,与之关联也删除 -nothing,删除关联数据,引发错误IntegrityError -删除关联数据,引发错误ProtectedError -删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空) -删除关联数据,与之关联的值设置为认值(前提FK字段需要设置认值) -删除关联数据, a. 与之关联的值设置为指定值,设置:models.SET(值) b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)
                                                    </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中<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>关联数据时,提供的条件:</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; 是否在<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>中创建外键约束</span>
    parent_link=False           <span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 在Admin中是否<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>关联数据</span>

<span style="color: #000000">

On<a href="/tag/eto/" target="_blank" class="keywords">eto</a>OneField(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; 要关联的表中的字段<a href="/tag/mingcheng/" target="_blank" class="keywords">名称</a></span>
    on_delete=None,<span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 当<a href="/tag/shanchu/" target="_blank" class="keywords">删除</a>关联表中的数据时,当前表与其关联的行的行为</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.当两个类之间有继承关系时,<a href="/tag/mo/" target="_blank" class="keywords">默</a>认会创建<a href="/tag/yige/" target="_blank" class="keywords">一个</a>一对一字段</span>
                                <span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 如下会在A表中额外<a href="/tag/zengjia/" target="_blank" class="keywords">增加</a><a href="/tag/yige/" target="_blank" class="keywords">一个</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中<a href="/tag/xianshi/" target="_blank" class="keywords">显示</a>关联数据时,提供的条件:</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; <a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a>第三张表时,使用字段用于指定关系表</span>
    through_fields=None,<span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; <a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a>第三张表时,使用字段用于指定关系表中那些字段做多对多关系表</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; 是否在<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>中创建外键约束</span>
    db_table=None,<span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; <a href="/tag/mo/" target="_blank" class="keywords">默</a>认创建第三张表时,<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a>中表的<a href="/tag/mingcheng/" target="_blank" class="keywords">名称</a></span>

<span style="color: #000000">
多表关系和参数

十,ORM操作

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
models.Tb1.objects.create(c1=,c2=) 增加一条数据,可以接受字典类型数据 **kwargs obj = models.Tb1(c1=,c2=<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=<span style="color: #800000">'
<span style="color: #800000">seven
<span style="color: #800000">'
) <span style="color: #008000">#
<span style="color: #008000"> 获取指定条件的数据

models.Tb1.objects.exclude(name=<span style="color: #800000">'
<span style="color: #800000">seven
<span style="color: #800000">'
) <span style="color: #008000">#
<span style="color: #008000"> 去除指定条件的数据

<span style="color: #008000">#<span style="color: #008000"> 删<span style="color: #008000">

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

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

bed3e286" class="code_img_closed" src="/res/2019/02-25/18/1c53668bcee393edac0d7b3b3daff1ae.gif" alt="">bed3e286" class="code_img_opened" style="display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
bed3e286" class="cnblogs_code_hide">
获取个数
                
    <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(id
lt=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(id__in=[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</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)

404cfe86" class="code_img_closed" src="/res/2019/02-25/18/1c53668bcee393edac0d7b3b3daff1ae.gif" alt="">404cfe86" class="code_img_opened" style="display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
404cfe86" class="cnblogs_code_hide">
arams=None,tables=None,order_by=None,select_params=None)

<span style="color: #008000">#<span style="color: #008000"> select和select_params是一组,where和params是一组,tables用来设置from哪个表<span style="color: #008000">

<span style="color: #008000"> Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"},select_params=(1,))<span style="color: #008000">

<span style="color: #008000"> Entry.objects.extra(where=['headline=%s'],params=['Lennon'])<span style="color: #008000">

<span style="color: #008000"> Entry.objects.extra(where=["foo='a' OR bar = 'a'","baz = 'a'"])<span style="color: #008000">

<span style="color: #008000"> Entry.objects.extra(select={'new_id': "select id from tb where id > %s"},),order_by=['-nid'])

<span style="color: #000000">
举个例子:
models.UserInfo.objects.extra(
select={<span style="color: #800000">'<span style="color: #800000">newid<span style="color: #800000">':<span style="color: #800000">'<span style="color: #800000">select count(1) from app01_usertype where id>%s<span style="color: #800000">'<span style="color: #000000">},select_params=[1<span style="color: #000000">,where = [<span style="color: #800000">'<span style="color: #800000">age>%s<span style="color: #800000">'<span style="color: #000000">],params=[18<span style="color: #000000">,order_by=[<span style="color: #800000">'<span style="color: #800000">-age<span style="color: #800000">'<span style="color: #000000">],tables=[<span style="color: #800000">'<span style="color: #800000">app01_usertype<span style="color: #800000">'<span style="color: #000000">]
)
<span style="color: #800000">"""<span style="color: #800000">
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
<span style="color: #800000">"""

<span style="color: #008000">#<span style="color: #008000"> 执行原生sql<span style="color: #008000">

<span style="color: #008000"> 更高灵活度的方式执行原生sql语句<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()

<span style="color: #000000">
高级操作

display: none" src="/res/2019/02-25/18/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">

<span style="color: #0000ff">def<span style="color: #000000"> all(self)
<span style="color: #008000">#<span style="color: #008000"> 获取所有的数据对象

<span style="color: #0000ff">def filter(self,**<span style="color: #000000">kwargs)
<span style="color: #008000">#<span style="color: #008000"> 条件查询
<span style="color: #008000">#<span style="color: #008000"> 条件可以是:参数,字典,Q

<span style="color: #0000ff">def exclude(self,**<span style="color: #000000">kwargs)
<span style="color: #008000">#<span style="color: #008000"> 条件查询
<span style="color: #008000">#<span style="color: #008000"> 条件可以是:参数,字典,Q

<span style="color: #0000ff">def select_related(self,*<span style="color: #000000">fields)
性能相关:表之间进行join连表操作,一次性获取关联的数据。

总结:
</span>1<span style="color: #000000"&gt;. select_related主要针一对一和多对一关系进行优化。
</span>2<span style="color: #000000"&gt;. select_related使用<a href="/tag/sql/" target="_blank" class="keywords">sql</a>的JOIN语句进行优化,通过减少<a href="/tag/SQLchaxun/" target="_blank" class="keywords">SQL查询</a>的<a href="/tag/cishu/" target="_blank" class="keywords">次数</a>来进行优化、提高<a href="/tag/xingneng/" target="_blank" class="keywords">性能</a>。

<span style="color: #0000ff">def prefetch_related(self,*<span style="color: #000000">lookups)
性能相关:多表连表操作时速度会慢,使用其执行多次SQL查询在Python代码中实现连表操作。

总结:
</span>1<span style="color: #000000"&gt;. 对于多对多字段(ManyToManyField)和一对多字段,可以使用prefetch_related()来进行优化。
</span>2<span style="color: #000000"&gt;. prefetch_related()的优化方式是分别<a href="/tag/chaxun/" target="_blank" class="keywords">查询</a>每个表,然后用Python处理他们之<a href="/tag/jiande/" target="_blank" class="keywords">间的</a>关系。

<span style="color: #0000ff">def annotate(self,**<span style="color: #000000">kwargs)
<span style="color: #008000">#<span style="color: #008000"> 用于实现聚合group by查询

<span style="color: #0000ff"&gt;from</span> django.db.models <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; Count,Avg,Sum

v </span>= models.UserInfo.objects.values(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;u_id</span><span style="color: #800000"&gt;'</span>).annotate(uid=Count(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;u_id</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;))
</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; SELECT u_id,COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id</span>

<span style="color: #000000">
v = models.UserInfo.objects.values(<span style="color: #800000">'<span style="color: #800000">u_id<span style="color: #800000">').annotate(uid=Count(<span style="color: #800000">'<span style="color: #800000">u_id<span style="color: #800000">')).filter(uid__gt=1<span style="color: #000000">)
<span style="color: #008000">#<span style="color: #008000"> SELECT u_id,COUNT(ui_id) AS uid FROM UserInfo GROUP BY u_id having count(u_id) > 1
<span style="color: #000000">
v = models.UserInfo.objects.values(<span style="color: #800000">'<span style="color: #800000">u_id<span style="color: #800000">').annotate(uid=Count(<span style="color: #800000">'<span style="color: #800000">u_id<span style="color: #800000">',distinct=True)).filter(uid__gt=1<span style="color: #000000">)
<span style="color: #008000">#<span style="color: #008000"> SELECT u_id,COUNT( DISTINCT ui_id) AS uid FROM UserInfo GROUP BY u_id having count(u_id) > 1

<span style="color: #0000ff">def distinct(self,*<span style="color: #000000">field_names)
<span style="color: #008000">#<span style="color: #008000"> 用于distinct去重
models.UserInfo.objects.values(<span style="color: #800000">'<span style="color: #800000">nid<span style="color: #800000">'<span style="color: #000000">).distinct()
<span style="color: #008000">#<span style="color: #008000"> select distinct nid from userinfo
<span style="color: #000000">
注:只有在Postgresql中才能使用distinct进行去重

<span style="color: #0000ff">def order_by(self,*<span style="color: #000000">field_names)
<span style="color: #008000">#<span style="color: #008000"> 用于排序
models.UserInfo.objects.all().order_by(<span style="color: #800000">'<span style="color: #800000">-id<span style="color: #800000">',<span style="color: #800000">'<span style="color: #800000">age<span style="color: #800000">'<span style="color: #000000">)

<span style="color: #0000ff">def extra(self,select_params=<span style="color: #000000">None)
<span style="color: #008000">#<span style="color: #008000"> 构造额外的查询条件或者映射,如:子查询
<span style="color: #000000">
Entry.objects.extra(select={<span style="color: #800000">'<span style="color: #800000">new_id<span style="color: #800000">': <span style="color: #800000">"<span style="color: #800000">select col from sometable where othercol > %s<span style="color: #800000">"},select_params=(1<span style="color: #000000">,))
Entry.objects.extra(where=[<span style="color: #800000">'<span style="color: #800000">headline=%s<span style="color: #800000">'],params=[<span style="color: #800000">'<span style="color: #800000">Lennon<span style="color: #800000">'<span style="color: #000000">])
Entry.objects.extra(where=[<span style="color: #800000">"<span style="color: #800000">foo='a' OR bar = 'a'<span style="color: #800000">",<span style="color: #800000">"<span style="color: #800000">baz = 'a'<span style="color: #800000">"<span style="color: #000000">])
Entry.objects.extra(select={<span style="color: #800000">'<span style="color: #800000">new_id<span style="color: #800000">': <span style="color: #800000">"<span style="color: #800000">select id from tb where id > %s<span style="color: #800000">"},order_by=[<span style="color: #800000">'<span style="color: #800000">-nid<span style="color: #800000">'<span style="color: #000000">])

<span style="color: #0000ff">def<span style="color: #000000"> reverse(self):
<span style="color: #008000">#<span style="color: #008000"> 倒序
models.UserInfo.objects.all().order_by(<span style="color: #800000">'<span style="color: #800000">-nid<span style="color: #800000">'<span style="color: #000000">).reverse()
<span style="color: #008000">#<span style="color: #008000"> 注:如果存在order_by,reverse则是倒序,如果多个排序则一一倒序

<span style="color: #0000ff">def defer(self,*<span style="color: #000000">fields):
models.UserInfo.objects.defer(<span style="color: #800000">'<span style="color: #800000">username<span style="color: #800000">',<span style="color: #800000">'<span style="color: #800000">id<span style="color: #800000">'<span style="color: #000000">)

models.UserInfo.objects.filter(...).defer(<span style="color: #800000">'<span style="color: #800000">username<span style="color: #800000">',<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">映射中排除某列数据

<span style="color: #0000ff">def only(self,*<span style="color: #000000">fields):
<span style="color: #008000">#<span style="color: #008000">仅取某个表中的数据
models.UserInfo.objects.only(<span style="color: #800000">'<span style="color: #800000">username<span style="color: #800000">',<span style="color: #800000">'<span style="color: #800000">id<span style="color: #800000">'<span style="color: #000000">)

models.UserInfo.objects.filter(...).only(<span style="color: #800000">'<span style="color: #800000">username<span style="color: #800000">',<span style="color: #800000">'<span style="color: #800000">id<span style="color: #800000">'<span style="color: #000000">)

<span style="color: #0000ff">def<span style="color: #000000"> using(self,alias):
指定使用的数据库,参数为别名(setting中的设置)

<span style="color: #008000">#<span style="color: #008000">#################################################<span style="color: #008000">

<span style="color: #008000"> PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #<span style="color: #008000">

<span style="color: #008000">#################################################

<span style="color: #0000ff">def raw(self,raw_query,translations=None,using=<span style="color: #000000">None):
<span style="color: #008000">#<span style="color: #008000"> 执行原生sql
models.UserInfo.objects.raw(<span style="color: #800000">'<span style="color: #800000">select * from userinfo<span style="color: #800000">'<span style="color: #000000">)

</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 如果<a href="/tag/sql/" target="_blank" class="keywords">sql</a>是其他表时,必须将名字设置为当前UserInfo对象的主键列名</span>
models.UserInfo.objects.raw(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;select id as nid from 其他表</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;)

</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 为原生<a href="/tag/sql/" target="_blank" class="keywords">sql</a>设置参数</span>
models.UserInfo.objects.raw(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;select id as nid from userinfo where nid><a href="/tag/s/" target="_blank" class="keywords">%s</a></span><span style="color: #800000"&gt;'</span>,p<a href="/tag/ara/" target="_blank" class="keywords">ara</a>ms=[12<span style="color: #000000"&gt;,])

</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 将<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>的到列名转换为指定列名</span>
name_map = {<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;f<a href="/tag/irs/" target="_blank" class="keywords">irs</a>t</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;f<a href="/tag/irs/" target="_blank" class="keywords">irs</a>t_name</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;last</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;last_name</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;bd</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;birth_date</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;pk</span><span style="color: #800000"&gt;'</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;}
Person.objects.raw(</span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;SELECT * FROM some_other_table</span><span style="color: #800000"&gt;'</span>,translations=<span style="color: #000000"&gt;name_map)

</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 指定<a href="/tag/shujuku/" target="_blank" class="keywords">数据库</a></span>
models.UserInfo.objects.raw(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;select * from userinfo</span><span style="color: #800000"&gt;'</span>,using=<span style="color: #800000"&gt;"</span><span style="color: #800000"&gt;default</span><span style="color: #800000"&gt;"</span><span style="color: #000000"&gt;)

</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt;################## 原生<a href="/tag/sql/" target="_blank" class="keywords">sql</a> ###################</span>
<span style="color: #0000ff"&gt;from</span> django.db <span style="color: #0000ff"&gt;import</span><span style="color: #000000"&gt; connection,connections
cursor </span>= connection.cursor()  <span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; cursor = connections['default'].cursor()</span>
cursor.execute(<span style="color: #800000"&gt;"""</span><span style="color: #800000"&gt;SELECT * from auth_user where id = <a href="/tag/s/" target="_blank" class="keywords">%s</a></span><span style="color: #800000"&gt;"""</span>,[1<span style="color: #000000"&gt;])
row </span>= cursor.fetchone() <span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; fetchall()/fetchmany(..)</span>

<span style="color: #0000ff">def values(self,*<span style="color: #000000">fields):
<span style="color: #008000">#<span style="color: #008000"> 获取每行数据为字典格式

<span style="color: #0000ff">def values_list(self,*fields,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 获取每行数据为元祖

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

  • year : 年-01-01
  • month: 年-月-01
  • day : 年-月-<span style="color: #000000">日
models.DatePlus.objects.dates(</span><span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;ctime</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;day</span><span style="color: #800000"&gt;'</span>,<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;DESC</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;)

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

</span><span style="color: #800000"&gt;"""</span><span style="color: #800000"&gt;
pip3 install pytz
import pytz
pytz.all_timezo<a href="/tag/nes/" target="_blank" class="keywords">nes</a>
pytz.timezone(‘Asia/Shanghai’)
</span><span style="color: #800000"&gt;"""</span>

<span style="color: #0000ff">def<span style="color: #000000"> none(self):
<span style="color: #008000">#<span style="color: #008000"> 空QuerySet对象

<span style="color: #008000">#<span style="color: #008000">###################################<span style="color: #008000">

<span style="color: #008000"> METHODS THAT DO DATABASE QUERIES #<span style="color: #008000">

<span style="color: #008000">###################################

<span style="color: #0000ff">def aggregate(self,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 聚合函数获取字典类型聚合结果
<span style="color: #0000ff">from django.db.models <span style="color: #0000ff">import<span style="color: #000000"> Count,Sum
result = models.UserInfo.objects.aggregate(k=Count(<span style="color: #800000">'<span style="color: #800000">u_id<span style="color: #800000">',distinct=True),n=Count(<span style="color: #800000">'<span style="color: #800000">nid<span style="color: #800000">'<span style="color: #000000">))
===> {<span style="color: #800000">'<span style="color: #800000">k<span style="color: #800000">': 3,<span style="color: #800000">'<span style="color: #800000">n<span style="color: #800000">': 4<span style="color: #000000">}

<span style="color: #0000ff">def<span style="color: #000000"> count(self):
<span style="color: #008000">#<span style="color: #008000"> 获取个数

<span style="color: #0000ff">def get(self,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 获取单个对象

<span style="color: #0000ff">def create(self,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 创建对象

<span style="color: #0000ff">def bulk_create(self,objs,batch_size=<span style="color: #000000">None):
<span style="color: #008000">#<span style="color: #008000"> 批量插入
<span style="color: #008000">#<span style="color: #008000"> batch_size表示一次插入的个数
objs =<span style="color: #000000"> [
models.DDD(name=<span style="color: #800000">'<span style="color: #800000">r11<span style="color: #800000">'<span style="color: #000000">),models.DDD(name=<span style="color: #800000">'<span style="color: #800000">r22<span style="color: #800000">'<span style="color: #000000">)
]
models.DDD.objects.bulk_create(objs,10<span style="color: #000000">)

<span style="color: #0000ff">def get_or_create(self,defaults=None,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 如果存在,则获取,否则,创建
<span style="color: #008000">#<span style="color: #008000"> defaults 指定创建时,其他字段的值
obj,created = models.UserInfo.objects.get_or_create(username=<span style="color: #800000">'<span style="color: #800000">root1<span style="color: #800000">',defaults={<span style="color: #800000">'<span style="color: #800000">email<span style="color: #800000">': <span style="color: #800000">'<span style="color: #800000">1111111<span style="color: #800000">',<span style="color: #800000">'<span style="color: #800000">u_id<span style="color: #800000">': 2,<span style="color: #800000">'<span style="color: #800000">t_id<span style="color: #800000">': 2<span style="color: #000000">})

<span style="color: #0000ff">def update_or_create(self,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 如果存在,则更新,否则,创建
<span style="color: #008000">#<span style="color: #008000"> defaults 指定创建时或更新时的其他字段
obj,created = models.UserInfo.objects.update_or_create(username=<span style="color: #800000">'<span style="color: #800000">root1<span style="color: #800000">',<span style="color: #800000">'<span style="color: #800000">t_id<span style="color: #800000">': 1<span style="color: #000000">})

<span style="color: #0000ff">def<span style="color: #000000"> first(self):
<span style="color: #008000">#<span style="color: #008000"> 获取一个

<span style="color: #0000ff">def<span style="color: #000000"> last(self):
<span style="color: #008000">#<span style="color: #008000"> 获取最后一个

<span style="color: #0000ff">def in_bulk(self,id_list=<span style="color: #000000">None):
<span style="color: #008000">#<span style="color: #008000"> 根据主键ID进行查找
id_list = [11,21,31<span style="color: #000000">]
models.DDD.objects.in_bulk(id_list)

<span style="color: #0000ff">def<span style="color: #000000"> delete(self):
<span style="color: #008000">#<span style="color: #008000"> 删除

<span style="color: #0000ff">def update(self,**<span style="color: #000000">kwargs):
<span style="color: #008000">#<span style="color: #008000"> 更新

<span style="color: #0000ff">def<span style="color: #000000"> exists(self):
<span style="color: #008000">#<span style="color: #008000"> 是否有结果
<span style="color: #000000">
其他操作

QuerySet方法大全

方法

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

相关推荐