1. 程式人生 > >django中的ContentType使用

django中的ContentType使用

types pos spa 會有 rom 作用 clas name 網上

contenttypes 是Django內置的一個應用,可以追蹤項目中所有app和model的對應關系,並記錄在ContentType表中。

每當我們創建了新的model並執行數據庫遷移後,ContentType表中就會自動新增一條記錄。如下:

技術分享圖片

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

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 冰箱滿減券 1 null null 3 面包狂歡節 null 1 null
""" name = models.CharField(max_length=32) electric_obj = models.ForeignKey(to=Electrics, null=True) food_obj = models.ForeignKey(to=Foods, null=True) cloth_obj = models.ForeignKey(to=Clothes, null=True)

如果是通用優惠券,那麽所有的ForeignKey為null,如果僅限某些商品,那麽對應商品ForeignKey記錄該商品的id,不相關的記錄為null。但是這樣做是有問題的:實際中商品品類繁多,而且很可能還會持續增加,那麽優惠券表中的外鍵將越來越多,但是每條記錄僅使用其中的一個或某幾個外鍵字段。

通過使用contenttypes 應用中提供的特殊字段GenericForeignKey,我們可以很好的解決這個問題。只需要以下三步:

  • 在model中定義ForeignKey字段,並關聯到ContentType表。通常這個字段命名為“content_type”
  • 在model中定義PositiveIntegerField字段,用來存儲關聯表中的主鍵。通常這個字段命名為“object_id”
  • 在model中定義GenericForeignKey字段,傳入上述兩個字段的名字。

為了更方便查詢商品的優惠券,我們還可以在商品類中通過GenericRelation字段定義反向關系。

class Electrics(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField(default=100)
    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)                 # step 1   關聯contentype表,使當前表與contenttype中的model的對應
    object_id = models.PositiveIntegerField()                        # step 2   對應model表中的id
    content_object = GenericForeignKey(content_type, object_id)  # step 3   (對應的表id,對應的表中的一條數據的id)

    def __str__(self):
        return self.name

# Coupon對象 - -----》商品對象
coupon_obj.content_object
# 商品對象 - -----》Coupon對象
electrics_obj.coupons.all()

GenericRelation反向查,GenericForeignKey正向查,都不會在數據庫中生成字段,只是方便查詢

django中的ContentType使用