1. 程式人生 > >Django的contenttypes應用、緩存相關

Django的contenttypes應用、緩存相關

主鍵 eric nas width 兩個 了解 ade return left

一、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應用、緩存相關