Django的contenttypes应用、缓存相关
一、django的contenttypes
contenttypes 是Django内置的一个应用 , 可以追踪项目中所有app 和 model 的对应关系, 并记录djang_content_type 表中.
每当我们创建了新的model 并执行数据库迁移后 , django_content_type 表中就会自动新增一条记录 , 比如我在应用pp01的models.py中创建表class Electrics(models.Model): pass。从数据库查看django_content_type表,显示如下:
id | app_label | model |
.... | admin,auth等内置应用 | .... |
4 | contenttypes | contenttype |
5 | app01 | electrics |
那么这个表有什么作用呢?这里提供一个场景,网上商城购物时,会有各种各样的优惠券,比如通用优惠券,满减券,或者是仅限特定品类的优惠券。在数据库中,可以通过外键将优惠券和不同品类的商品表关联起来:
from django.db import models class Electrics(models.Model):
"""
id name
1 日立冰箱
2 三星电视
3 小天鹅洗衣机
"""
name = models.CharField(max_length=32) class Foods(models.Model):
"""
id name
1 面包
2 烤鸭
"""
name = models.CharField(max_length=32) class Clothes(models.Model):
name = models.CharField(max_length=32) class Coupon(models.Model):
"""
id name Electrics Foods Clothes more...
1 通用优惠券 null null null
2 冰箱满减券 2 null null
3 面包狂欢节 null 1 null """
name = models.CharField(max_length=32)
electric = models.ForeignKey(to='Electrics', null=True, on_delete=models.CASCADE)
food = models.ForeignKey(to='Foods', null=True, on_delete=models.CASCADE)
cloth = models.ForeignKey(to='Clothes', null=True, on_delete=models.CASCADE)
如果是通用优惠券,那么所有的ForeignKey为null,如果仅限某些商品,那么对应商品ForeignKey记录该商品的id,不相关的记录为null。但是这样做是有问题的:实际中商品品类繁多,而且很可能还会持续增加,那么优惠券表中的外键将越来越多,但是每条记录仅使用其中的一个或某几个外键字段。
通过使用contenttypes 应用中提供的特殊字段GenericForeignKey,我们可以很好的解决这个问题。只需要以下三步:
- 在model中定义ForeignKey字段,并关联到ContentType表。通常这个字段命名为“content_type”;
- 在model中定义PositiveIntegerField字段,用来存储关联表中的主键。通常这个字段命名为“object_id”;
- 在model中定义GenericForeignKey字段,传入上述两个字段的名字;
为了更方便查询商品的优惠券,我们还可以在商品类中通过GenericRelation字段定义反向关系。
示例代码如下:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey class Electrics(models.Model):
name = models.CharField(max_length=32)
coupons = GenericRelation(to='Coupon') # 用于反向查询,不会生成表字段 def __str__(self):
return self.name class Foods(models.Model):
name = models.CharField(max_length=32)
coupons = GenericRelation(to='Coupon') def __str__(self):
return self.name class Clothes(models.Model):
name = models.CharField(max_length=32)
coupons = GenericRelation(to='Coupon') def __str__(self):
return self.name class Coupon(models.Model):
name = models.CharField(max_length=32) content_type=models.ForeignKey(to=ContentType, on_delete=models.CASCADE) # step1
object_id=models.PositiveIntegerField() # step2
content_object=GenericForeignKey('content_type', 'object_id') # step3 def __str__(self):
return self.name
ContentType表对象有model_class() 方法,能取到对应model,如下:
content = ContentType.objects.filter(app_label='app01', model='electrics').first()
electrics_class = content.model_class() # electrics_class 就相当于models.Electrics
res = electrics_class.objects.all()
print(res) # res表示electrics表中的所有对象
以下是表操作示例:
# 为三星电视(id=2)创建一条优惠记录
s_tv = models.Electrics.objects.filter(id=2).first()
models.Coupon.objects.create(name='电视优惠券', content_object=s_tv) # 查询优惠券(id=1)绑定了哪些商品
coupon_obj = models.Coupon.objects.filter(id=1).first()
prod = coupon_obj.content_object # 查询三星电视(id=2)的所有优惠券
res = s_tv.coupons.all() # 查询obj的所有优惠券:如果没有定义反向查询字段,通过如下方式:
content = ContentType.objects.filter(app_label='app01', model='model_name').first()
res = models.OftenAskedQuestion.objects.filter(content_type=content, object_id=obj.pk).all()
总结:当一张表和多个表FK关联,并且多个FK中只能选择其中一个或其中n个时,可以利用contenttypes应用,只需定义三个字段就搞定!
二、django的缓存相关
有时候你不想缓存一个页面,甚至不想某个页面的一部分,只是想缓存某个数据库检索的结果,django提供了底层次的API,你可以是用这些API来缓存任何粒度的数据,
如果你想了解所有的API, 强烈建议你去看django\core\cache\backends目录下的cache.py文件,这里仅仅列举一些简单的用法:
from django.core.cache import cache
cache.set('token', 'safrgerjge') # 在缓存中设置一个类似字典的键值对
cache.get('token') # 通过键取出值
'safrgerjge'
cache.set('token', 'safrgerjge', 5) # 第三个参数代表过期时间,5秒后清除
cache.get('token') # 在5秒内取出,可以取出对应的值
'safrgerjge'
cache.get('token') # 超过5秒,键值被清除
cache.get('token')
Django的contenttypes应用、缓存相关的更多相关文章
- django缓存相关
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/weixin_39726347/articl ...
- Django: 之用户注册、缓存和静态网页
Django 用户注册系统 Django 的源码中已经有登录,退出,重设密码等相关的视图函数,在下面这个app中 django.contrib.auth 可以点击对应的版本查看相关源代码:1.9 1 ...
- django之中间件、缓存、信号、admin内置后台
目录: 中间件 缓存 信号 admin后台 一.中间件 1.什么是中间件? 中间件是一个.一个的管道,如果相对任何所有的通过Django的请求进行管理都需要自定义中间件 中间件可以对进来的请求和出去的 ...
- contenttype应用 , 缓存相关
一. Django的contenttypes contenttypes 是Django内置的一个应用,可以追踪项目中所有 app和model 的对应关系,并记录在 django_content_typ ...
- Web框架之Django_01初识(三大主流web框架、Django安装、Django项目创建方式及其相关配置、Django基础三件套:HttpResponse、render、redirect)
摘要: Web框架概述 Django简介 Django项目创建 Django基础必备三件套(HttpResponse.render.redirect) 一.Web框架概述: Python三大主流Web ...
- 在ubuntu16中部署Django使用memcached作为缓存
Django支持很多缓存系统,如 文件系统缓存. 数据库缓存. 内存缓存(Memcached),其中,Memcached是最快的,没有之一,是绝配.因为所有的缓存数据都放在内存,没有了IO延迟,也没有 ...
- Django学习之站点缓存详解
本文和大家分享的主要是django缓存中站点缓存相关内容,一起来看看吧,希望对大家学习django有所帮助. 缓存整个站点,是最简单的缓存方法 在 MIDDLEWARE_CLASSES 中加入 “ ...
- Django之使用redis缓存session,历史浏览记录,首页数据实现性能优化
Redis缓存session 配置Django缓存数据到redis中 # diango的缓存配置 CACHES = { "default": { "BACKEND&quo ...
- redis的介绍与操作及Django中使用redis缓存
redis VS mysql的区别 """ redis: 内存数据库(读写快).非关系型(操作数据方便) mysql: 硬盘数据库(数据持久化).关系型(操作数据间关系) ...
随机推荐
- Android 编程 AMapLocationClientOption 类中的 setNeedAddress 方法用处 (高德地图 com.amap.api.location.AMapLocationClientOption 中的类)
最近在用高德地图来写Android App, 其中有一些 方法是不太理解的,这里写一下 对 高德地图 com.amap.api.location.AMapLocationClientOption ...
- apk系统签名命令
java -jar signapk.jar platform.x509.pem platform.pk8 D:/ClockSetting.apk D:/ClockSettingSigned.apk 需 ...
- java 实现共享锁和排它锁
一直对多线程有恐惧,在实现共享锁和排它锁之后,感觉好了很多. 共享锁 就是查询的时候,如果没有修改,可以支持多线程查询: 排它锁 就是修改的时候,锁定共享锁,停止查询,同时,锁定排它锁,只 ...
- Typescript : 遍历Array的方法:for, forEach, every等
方法一,for…of 这个貌似是最常用的方法,angular 2中HTML语法绑定也是要的这种语法. let someArray = [1, "string", false]; f ...
- BZOJ4518 Sdoi2016 征途 【斜率优化DP】 *
BZOJ4518 Sdoi2016 征途 Description Pine开始了从S地到T地的征途. 从S地到T地的路可以划分成n段,相邻两段路的分界点设有休息站. Pine计划用m天到达T地.除第m ...
- python(八):反射
反射机制是通过python3内置的hasattr.getattr.setattr来实现的.即根据变量名的字符串形式来获取变量名的属性或方法. 一.通过反射查看已知对象的属性和方法 getattr(ob ...
- 《DSP using MATLAB》示例Example 9.5
代码: %% ------------------------------------------------------------------------ %% Output Info about ...
- 《DSP using MATLAB 》示例Example6.3
代码: C0 = 0; B1 = [2 4; 3 1]; A1 = [1 1 0.9; 1 0.4 -0.4]; B2 = [0.5 0.7; 1.5 2.5; 0.8 1]; A2 = [1 -1 ...
- 《DSP using MATLAB》示例Example 6.10
上代码: % Pole-Zero IIR filter to Lattice-ladder structure filter b = [1, 2, 2, 1]; a = [1, 13/24, 5/8, ...
- ballerina 学习十六 错误&&异常处理
ballerina 的error 处理和elxiir 以及rust 比较类似使用模式匹配,但是他的 error lifting 还是比较方便的 同时check 也挺好,异常处理没什么特殊的 throw ...