Django的Contenttypes应用,缓存相关
一.django的contenttypes
contenttypes是django内置的一个应用,可以追踪项目中所有app和model的对应关系,并记录在django_content_type表中
每当我们创建新的model并执行数据库迁移后,django_content_type表中就会自动新增一条记录,我们新建一个项目,先不创建表结构,直接迁移数据库,就会生成一个django_content的表

可以看到默认的admin,auth,session等内置应用等,我们来添加一个应用并创建一些表模型,同步迁移后,在看看contenttypes表的变化

会发现应用中的每个模型类都对应有一条记录生成,这些数据配合一些语法会在一些特定的场景优化程序的设计模式。
我们看下面一个场景:
网上商城购物时,会有各种各样的优惠券,比如通用优惠券,满减券,或者是仅限特定品类的优惠券。在数据库中,可以通过外键将优惠券和不同品类的商品表关联起来:
from django.db import models class Electrics(models.Model): """ id name 日立冰箱 三星电视 小天鹅洗衣机 """ name = models.CharField(max_length=32) class Foods(models.Model): """ id name 面包 烤鸭 """ 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... 通用优惠券 null null null 冰箱满减券 2 null null 面包狂欢节 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)
coupon表中,如果是通用优惠券,那么所有的ForeignKey为null;如果仅限某些商品,那么对应商品ForeignKey记录该商品的ID,不相关的记录为null。但是这样做的问题是:实际中商品种类繁多,而且很可以持续增加,那么优惠券表中的外键字段越来越多,但是每条记录仅使用其中的一个或某几个外籍字段,这样会导致每条coupon记录的字段越来越多,且空间使用率越来越低。
在这里就可以使用contenttypes应用中提供的特殊字段GenericForeignKey,我们可以很好的解决这个问题,只需要以下三步:
-在coupon model中定义ForeignKey字段,关联到contenttype表。通常这个字段命名为content_type;
-在coupon model中定义PositiveIntegerField字段,用来存储关联表中的主键。通常这个字段命名为object_id.
-在coupon model中定义GenericForeignKey字段,传入上述两个字段的名字。
为了更方便查询商品的优惠券,我们还可以在商品类中通过GenericRelation字段定义反向关系。
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation 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,如下:
def contenttypes_get(request): content = ContentType.objects.filter(app_label='app01', model='electrics').first() electrics_class = content.model_class() # 得到模型对象 res = electrics_class.objects.all() #相当于Electrics.object.all() print(res) # <QuerySet [<Electrics: 小米电视>, <Electrics: 格力空调>]> return HttpResponse('OK')
以下是表操作示例:
# 为小米电视创建一张优惠券 s_tv = Electrics.objects.filter(name='小米电视').first() Coupon.objects.create(name='小米电视优惠券', content_object=s_tv) # 查询优惠券绑定了哪些商品 coupon_obj = Coupon.objects.filter(id=1).first() pro_obj = coupon_obj.content_object print(pro_obj) # 查询小米电视所有的优惠券 res = s_tv.coupons.all() print(res) # <QuerySet [<Coupon: 小米电视优惠券>]>
总结:当一张表和多个表FK关联,并且多个FK中只能选择其中一个或者其中n个时,可以利用contenttypes应用,只需要定义这三个字段就可以搞定!
二.django的缓存相关
有时有你不想缓存一个页面,甚至不想某个页面的一部分,只是想缓存某个数据库检索的结果,djang提供了底层的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')
浙公网安备 33010602011771号