使用场景

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

Customer模型:

class Customer(models.Model):

    name = models.CharField(max_length=32)
qq = models.CharField(max_length=64,unique=True)
weixin = models.CharField(max_length=64,blank=True,null=True)
age = models.PositiveSmallIntegerField(blank=True,null=True)
referral_from = models.ForeignKey("Customer",related_name="my_referrals",
blank=True,null=True,verbose_name="转介绍",on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True) #auto_now_add自动增加 def __str__(self):
return self.name class Meta:
verbose_name_plural = "客户信息表"
verbose_name = "客户信息表" ----------------------------------------------------------
Enrollment模型:
class Enrollment(models.Model):
"""学员报名信息"""
customer = models.ForeignKey("Customer",on_delete=models.CASCADE,related_name='entries')
class_grade = models.ForeignKey("ClassList",on_delete=models.CASCADE)
enrollment_date = models.DateField()
def __str__(self):
#return self.customer class Meta:
unique_together = ("customer","class_grade")
---------------------------------------------------------------------------
FollowUpRecord模型
class FollowUpRecord(models.Model):
customer = models.ForeignKey("Customer",on_delete=models.CASCADE)
content = models.TextField(max_length=1024)
def __str__(self):
return "%s" % self.customer
----------------------------------------------------------------------------
ClassList模型:
class ClassList(models.Model):
semester = models.PositiveSmallIntegerField(verbose_name="学期")
class_type_choices = ((0,'脱产'),(1,'周末'),(2,'网络'))
start_date = models.DateField()
end_date = models.DateField() -----------------------------------------------------------------------------------------------------------

一、单表查询

models.Tb1.objects.create(c1='xx', c2='oo')

增加一条数据,可以接受字典类型数据 **kwargs

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

models.Tb1.objects.get(id=123) # 获取单条数据,不存在则报错(不建议)

models.Tb1.objects.all() # 获取全部

models.Tb1.objects.filter(name='seven') # 获取指定条件的数据

models.Tb1.objects.exclude(name='seven') # 获取指定条件的数据

models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据

models.Tb1.objects.filter(name='seven').update(gender='0') # 将指定条件的数据更新,均支持 **kwargs

obj = models.Tb1.objects.get(id=1)

obj.c1 = '111'

obj.save()

二、查询简单操作

获取个数

models.Tb1.objects.filter(name='seven').count()

大于,小于

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

in

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

isnull
Entry.objects.filter(pub_date__isnull=True)

contains

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

range

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

其他类似

startswith,istartswith, endswith, iendswith,

order by

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

group by--annotate

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

limit 、offset

models.Tb1.objects.all()[10:20]

regex正则匹配,iregex 不区分大小写

Entry.objects.get(title__regex=r'^(An?|The) +')
Entry.objects.get(title__iregex=r'^(an?|the) +')

date

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

year

Entry.objects.filter(pub_date__year=2005)
Entry.objects.filter(pub_date__year__gte=2005)

month

Entry.objects.filter(pub_date__month=12)
Entry.objects.filter(pub_date__month__gte=6)

day

Entry.objects.filter(pub_date__day=3)
Entry.objects.filter(pub_date__day__gte=3)

week_day

Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2)

hour

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

minute

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

second

Event.objects.filter(timestamp__second=31)
Event.objects.filter(time__second=2)
Event.objects.filter(timestamp__second__gte=31)

三、一对多 使用ForeignKey查询

约束 节省硬盘 但是多表查询会降低速度,大型程序反而不使用外键,而是用单表(约束的时候,通过代码判断)

正向查询

关系模型Enrollment包含关联模型Customer的ForeignKey, 模型Enrollment的实例可以通过关联字段访问Customer实例:

查:

>>> e = Enrollment.objects.get(id=2)         #注意:此处不能用e =Enrollment.objects.filter(id=2)

>>> e.customer                                          # 通过上查询到的e对象,关联字段( e.customer )访问到Customer实例

e.customer并调用save方法存入数据库

>>> e.customer= some_customer

>>> e.save()

如果ForeignKey 字段有null=True 设置(即它允许NULL值),可以分配None来删除对应的关联性

>>> e.customer= null

>>> e.save()


反向查询

已经得到模型Customer的实例,需要查询该以该实例为外键的相关模型(如FollowUpRecord和Enrollment),可以使用查询集API取出相应的实例。

外键没有指定related_name的相关模型:FollowUpRecord

>>> customer = models.ForeignKey("Customer",on_delete=models.CASCADE)

反查找使用 模型类名小写_set.all() ,方法如下:

>>>  c = Customer.objects.get(id=1)

>>>  c.followuprecord_set.all()

外键指定related_name的相关模型:FollowUpRecord

customer = models.ForeignKey("Customer",on_delete=models.CASCADE,related_name='entries')
反查找不能使用 模型类名小写_set.all(),需要使用related_name的值,方法如下:

>>>  c = Customer.objects.get(id=1)

>>>  c.entries.all()

三、多对多 ManyToMany

class UserGroup(models.Model):
caption = models.CharField(max_length=64)
user_info = models.ManyToManyField('UserInfo')
def __unicode__(self):
return self.caption

user_info_obj = models.UserInfo.objects.get(name='alisa')
user_info_objs = models.UserInfo.objects.all()

group_obj = models.UserGroup.objects.get(caption='CEO')
group_objs = models.UserGroup.objects.all()

# 添加数据
#group_obj.user_info.add(user_info_obj)

group_obj.user_info.add(*user_info_objs)

#例:1,2,3分别代表user_info.的主键id

group_obj.user_info.add(1,2,3)

group_obj.user_info.add([1,2,3])

# 删除数据
#group_obj.user_info.remove(user_info_obj)
#group_obj.user_info.remove(*user_info_objs)

#例:1,2,3分别代表user_info.的主键id

group_obj.user_info.remove(1,2,3)

group_obj.user_info.remove([1,2,3])

# 反向添加数据
#user_info_obj.usergroup_set.add(group_obj)
#user_info_obj.usergroup_set.add(*group_objs)

# 反向删除数据
#user_info_obj.usergroup_set.remove(group_obj)
#user_info_obj.usergroup_set.remove(*group_objs)

# 获取数据
#print group_obj.user_info.all()
#print group_obj.user_info.all().filter(id=1)

#反向 获取数据
#print user_info_obj.usergroup_set.all()
#print user_info_obj.usergroup_set.all().filter(caption='CEO')
#print user_info_obj.usergroup_set.all().filter(caption='DBA')

django model 操作总结的更多相关文章

  1. Django model操作

    一.各种查询统计操作   def all(self) # 获取所有的数据对象 def filter(self, *args, **kwargs) # 条件查询 # 条件可以是:参数,字典,Q def ...

  2. Django之Model操作

    Django之Model操作 本节内容 字段 字段参数 元信息 多表关系及参数 ORM操作 1. 字段 字段列表 AutoField(Field) - int自增列,必须填入参数 primary_ke ...

  3. Django数据操作F和Q、model多对多操作、Django中间件、信号、读数据库里的数据实现分页

    models.tb.objects.all().using('default'),根据using来指定在哪个库里查询,default是settings中配置的数据库的连接名称. 外话:django中引 ...

  4. Python之路【第二十二篇】:Django之Model操作

    Django之Model操作   一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bi ...

  5. Day19 Django之Form表单验证、CSRF、Cookie、Session和Model操作

    一.Form表单验证 用于做用户提交数据的验证1.自定义规则 a.自定义规则(类,字段名==html中的name值)b.数据提交-规则进行匹配代码如下: """day19 ...

  6. Django(八)下:Model操作和Form操作、序列化操作

    二.Form操作 一般会创建forms.py文件,单独存放form模块. Form 专门做数据验证,而且非常强大.有以下两个插件: fields :验证(肯定会用的) widgets:生成HTML(有 ...

  7. Django(八)上:Model操作和Form操作

    ↑↑↑点上面的”+”号展开目录 Model和Form以及ModelForm简介 Model操作: 创建数据库表结构 操作数据库表 做一部分的验证 Form操作: 数据验证(强大) ModelForm ...

  8. Python之路-(Django(csrf,中间件,缓存,信号,Model操作,Form操作))

    csrf 中间件 缓存 信号 Model操作 Form操作 csrf: 用 django 有多久,我跟 csrf 这个概念打交道就有久了. 每次初始化一个项目时都能看到 django.middlewa ...

  9. 03: Django Model数据库操作

    目录:Django其他篇 01:Django基础篇 02:Django进阶篇 03:Django数据库操作--->Model 04: Form 验证用户数据 & 生成html 05:Mo ...

随机推荐

  1. linux/work

    0.切换用户 //默认root用户是无固定密码的,并且是被锁定的,如果想给root设置一个密码 sudo passwd root //输入密码 & 确认密码 //切换root用户 su roo ...

  2. SpringBoot 使用 RestTemplate 调用exchange方法 显示错误信息

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  3. PhoneGap学习网址

    官网:http://app-framework-software.intel.com/ 下载地址:http://download.csdn.net/download/haozq2012/7635951

  4. Eclipse连接SQL Server 2008数据库

    一.准备材料 要能够使用数据库就要有相应的JDBC,所以我们要去Microsoft官网下载 https://www.microsoft.com/zh-cn/download/details.aspx? ...

  5. Tomcat 一台机器运行多个Tomcat

    转 https://www.cnblogs.com/andy1234/p/8866588.html 在一台Win10 PC 上面同时开启两个Tomcat系统为例. 1. 硬件环境 2. 到Tomcat ...

  6. 【已解决】Error running 'xxx项目' Command line is too long(idea版)

    [错误] Error running 'xxx项目': Command line is too long. Shorten command line for xxx or also for Sprin ...

  7. 如何增强Linux和Unix服务器系统安全性

    众所周知,网络安全是一个非常重要的课题,而 Linux 和 unix 又是一种服务器上运行最广告的操作系统,下面本文将就加强一些适当的配置来防止一些安全问题的发生,以增强Linux/Unix服务器系统 ...

  8. JAVA中自定义properties文件介绍

    Gradle中的使用 1. 使用gradle.properties buid.gradle 和 gradle.properties可以项目使用,在同一个项目中,build.gradle可以直接获取其同 ...

  9. django基础篇01-环境的搭建和项目的创建

    本文参考自银角大王的博客 基本配置 常用命令: django-admin startproject xxx(项目名) python3 manage.py startapp xxx(app名) pyth ...

  10. oracle给用户赋dblink权限

    create database link 别名(可任意起) connect to 需要连接库的用户名identified by 需要连接库的用户名 using '(DESCRIPTION =(ADDR ...