Django的contenttypes應用、緩存相關

1、django的contenttypes

  contenttypes是Django內置的一個應用,能夠追蹤項目中全部app和model的對應關係,並記錄在django_content_type表中。python

  每當咱們建立了新的model並執行數據庫遷移後,django_content_type表中就會自動新增一條記錄。好比我在應用app01的models.py中建立表class Electrics(models.Model): pass。從數據庫查看django_content_type表,顯示以下:數據庫

iddjango

app_label緩存

modelapp

....spa

admin, auth等內置應用code

......對象

4blog

contenttypestoken

contenttype

5

app01

electrics

  那麼這個表有什麼做用呢?這裏提供一個場景,網上商城購物時,會有各類各樣的優惠券,好比通用優惠券,滿減券,或者是僅限特定品類的優惠券。在數據庫中,能夠經過外鍵將優惠券和不一樣品類的商品表關聯起來:

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)

  若是是通用優惠券,那麼全部的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應用,只需定義三個字段就搞定!

2、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' )
相關文章
相關標籤/搜索