加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Django:Django中的ORM

发布时间:2020-12-15 17:16:41 所属栏目:大数据 来源:网络整理
导读:一、Django项目使用MySQL数据库 1,在Django项目的settings.py,文件中,配置数据库连接信息: DATABASES = : : , : : : : 3306 2,在Django项目中__init__.py文件中写如下代码,告诉Django使用pymysql模块连接MySQL数据库: pymysql.install_as_MySQLdb()

一、Django项目使用MySQL数据库

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

DATABASES =: : , : : : : 3306

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

pymysql.install_as_MySQLdb()

二,Model

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

基本情况:

  • 每个模型都是一个Python类,它是django.db.models.Model的子类。
  • 模型的每个属性都代表一个数据库字段。
  • 综上所述,Django为您提供了一个自动生成的数据库访问API

三,快速入门

下面这个例子定义了一个?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及更高版本。

四,字段

- int自增列,必须填入参数 primary_key=BigAutoField(AutoField) </span>- bigint自增列,必须填入参数 primary_key=<span style="color: #000000"&gt;True 注:当model中如果没有自增列,则自动会创建一个列名为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; 自动创建一个列名为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; 自定义自增列</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,开启此功能,需要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中提供验证支持 字母、数字、下划线、连接符(减号) CommaSeparatedIntegerField(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中提供读取文件夹下文件的功能 </span>-<span style="color: #000000"&gt; 参数: path,文件夹路径 match</span>=<span style="color: #000000"&gt;None,正则匹配 recursive</span>=<span style="color: #000000"&gt;False,递归下面的文件夹 allow_files</span>=<span style="color: #000000"&gt;True,允许文件 allow_folders</span>=<span style="color: #000000"&gt;False,允许文件夹 FileField(Field) </span>-<span style="color: #000000"&gt; 字符串,路径保存在数据库,文件上传到指定目录 </span>-<span style="color: #000000"&gt; 参数: upload_to </span>= <span style="color: #800000"&gt;""</span><span style="color: #000000"&gt; 上传文件的保存路径 storage </span>=<span style="color: #000000"&gt; None 存储组件,默认django.core.files.storage.FileSystemStorage ImageField(FileField) </span>-<span style="color: #000000"&gt; 字符串,路径保存在数据库,文件上传到指定目录 </span>-<span style="color: #000000"&gt; 参数: upload_to </span>= <span style="color: #800000"&gt;""</span><span style="color: #000000"&gt; 上传文件的保存路径 storage </span>=<span style="color: #000000"&gt; None 存储组件,默认django.core.files.storage.FileSystemStorage width_field</span>=<span style="color: #000000"&gt;None,上传图片的高度保存的数据库字段名(字符串) height_field</span>=<span style="color: #000000"&gt;None 上传图片的宽度保存的数据库字段名(字符串) 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; 长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型 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()实例。

五,自定义字段

(self,max_length,*args,**=(max_length=max_length,**</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; 限定生成数据库表的字段类型为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(%s)</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)

六,注意事项

1 = 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方法是一个钩子,可用于定制操作,如:上述的异常处理。</span> 2<span style="color: #000000"&gt;.Admin中修改错误提示 </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;required</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; Meta: 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)

注意事项

七,字段参数

verbose_name Admin中显示的字段名称 blank Admin中是否允许用户输入为空 editable Admin中是否可以编辑 help_text Admin中该字段的提示信息 choices Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作 如: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 自定义错误信息(字典类型),从而定制想要显示的错误信息; 字典健: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;格式错误</span><span style="color: #800000"&gt;'</span><span style="color: #000000"&gt;} validators 自定义错误验证(列表类型),从而定制想要的验证规则 </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;错误了</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_112233d+</span><span style="color: #800000"&gt;'</span>,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;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;又错误了</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;),] )

字段参数

八,元信息

= models.AutoField(primary_key== models.CharField(max_length=32 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中显示的表名称</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

元信息

九,多表关系和参数

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>

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

十,ORM操作

models.Tb1.objects.create(c1=,c2=) 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"> 修改单条数据

    <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</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)

<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">
高级操作

<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使用SQL的JOIN语句进行优化,通过减少SQL查询的次数来进行优化、提高性能。

<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()的优化方式是分别查询每个表,然后用Python处理他们之间的关系。

<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(uidgt=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; 如果SQL是其他表时,必须将名字设置为当前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; 为原生SQL设置参数</span>
models.UserInfo.objects.raw(<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;select id as nid from userinfo where nid>%s</span><span style="color: #800000"&gt;'</span>,params=[12<span style="color: #000000"&gt;,])

</span><span style="color: #008000"&gt;#</span><span style="color: #008000"&gt; 将获取的到列名转换为指定列名</span>
name_map = {<span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;first</span><span style="color: #800000"&gt;'</span>: <span style="color: #800000"&gt;'</span><span style="color: #800000"&gt;first_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; 指定数据库</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;################## 原生SQL ###################</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 = %s</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_timezones
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">2222211<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方法大全

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读