contenttype应用 , 缓存相关
一. Django的contenttypes
contenttypes 是Django内置的一个应用,可以追踪项目中所有 app和model 的对应关系,并记录在 django_content_type 表中.
每当我们创建了新的model 并执行数据库迁移后,django_content_type 表中就会自动新增一条记录. 比如我在应用 app01 的model.py 中创建了 class Electrics(models.Model): pass。从数据库查看django_content_type表,显示如下:

那么这个表有什么作用呢?这里提供一个场景,网上商城购物时,会有各种各样的优惠券,比如通用优惠券,满减券,或者是仅限特定品类的优惠券。在数据库中,可以通过外键将优惠券和不同品类的商品表关联起来:
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文件,这里仅仅列举一些简单的用法:
|
1
2
3
4
5
6
7
8
9
|
>>> 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') |
contenttype应用 , 缓存相关的更多相关文章
- Django的contenttypes应用、缓存相关
一.django的contenttypes contenttypes 是Django内置的一个应用 , 可以追踪项目中所有app 和 model 的对应关系, 并记录djang_content_typ ...
- http中有关缓存相关的几个字段
转载自:http://blog.csdn.net/lifeibo/article/details/5979572 Expires.Cache-Control.Last-Modified. ETag是R ...
- 浏览器缓存相关http头
近期看雅虎黄金34条,学习下优化站点性能的方法. 当中有一条:"为文件头指定Expires或Cache-Control",详细来说指对于静态内容:设置文件头过期时间Expires的 ...
- 《前端之路》之 Cookie && localStorage && Session Storage 缓存相关
08: Cookie && localStorage && Session Storage 缓存相关 客户端.前端 存储 一. 起 因 首先解释下为什么想来写这个关于前 ...
- Java缓存相关memcached、redis、guava、Spring Cache的使用
随笔分类 - Java缓存相关 主要记录memcached.redis.guava.Spring Cache的使用 第十二章 redis-cluster搭建(redis-3.2.5) 摘要: redi ...
- MySQL的Innodb缓存相关优化
MySQL的Innodb缓存相关优化 INNODB 状态的部分解释 通过 命令 SHOW STATUS LIKE 'Innodb_buffer_pool_%' 查看 Innodb缓存使用率 (I ...
- 网页缓存相关的HTTP头部信息详解
前言 之前看完了李智慧老师著的<大型网站技术架构-核心原理与案例分析>这本书,书中多次提起浏览器缓存的话题,恰是这几天生产又遇到了一个与缓存的问题,发现自己书是没少看,正经走心的内容却不多 ...
- 浏览器缓存相关的Http头介绍:Expires,Cache-Control,Last-Modified,ETag
转自:http://www.path8.net/tn/archives/2745 缓存对于web开发有重要作用,尤其是大负荷web系统开发中. 缓存分很多种:服务器缓存,第三方缓存,浏览器缓存等.其中 ...
- ios 缓存相关信息收集
链接:http://www.cnblogs.com/pengyingh/category/353093.html 使用NSURLCache让本地数据来代替远程UIWebView请求 摘要: 原文作者: ...
随机推荐
- [置顶]
django快速获取项目所有的URL
django快速获取项目所有的URL django1.10快速获取项目所有的URL列表,可以用于权限控制 函数如下: import re def get_url(urllist , parent='' ...
- JS: document.getElementBy(), setInerval()
ylbtech-JavaScript-DOM document.getElementBy(),setInerval() 1.A,document.getElementBy()返回顶部 document ...
- MFC 消息类型
标准(窗口)消息:窗口消息一般与窗口内部运作有关,如创建窗口,绘制窗口,销毁窗口,通常,消息是从系统发到窗口,或从窗口发到系统.发送函数SendMessage()或者PostMessage().除WM ...
- JavaScript学习与实践一
一.JavaScript数组 创建JavaScript数组有两种方式 方式一: var cars=new Array(); cars[0]="Audi"; cars[1]=&quo ...
- 微信开源组件WCDB漫谈及Demo
代码地址如下:http://www.demodashi.com/demo/12422.html 前言 移动端的数据库选型一直是一个难题,直到前段时间看到了WeMobileDev(微信前端团队)放出了第 ...
- javascript 关于弹出新页面始终在正中央方法
记录一个关于弹出新页面始终在正中央方法 function openwindow(url, name, iWidth, iHeight) { var url; ...
- C#命名空间大全详细教程
www.51rgb.com System 命名空间包含了定义数据类型.事件和事件处理程序等基本类: System.Data 命名空间包含了提供数据访问功能的命名空间和类: System.IO 命名空间 ...
- json解析:[1]gson解析json
客户端与服务器进行数据交互时,常常需要将数据在服务器端将数据转化成字符串并在客户端对json数据进行解析生成对象.但是用jsonObject和jsonArray解析相对麻烦.利用Gson和阿里的fas ...
- 一文了解ConfigurationConditon接口
ConfigurationCondition 接口说明 @Conditional 和 Condition 在了解ConfigurationCondition 接口之前,先通过一个示例来了解一下@C ...
- 全命令行手写MapReduce并且打包运行
主要要讲的有3个 java中的package是干啥的? 工作了好几年的都一定真正理解java里面的package关键字,这里在写MapReduce需要进行打包的时候突然发现命令行下打包运行居然不会了, ...