1. 程式人生 > >Django ContentType元件 需求

Django ContentType元件 需求

ContentType元件

遇到這一張表要跟多張表進行外來鍵關聯的時候~我們Django提供了ContentType元件~

ContentType是Django的內建的一個應用,可以追蹤專案中所有的APP和model的對應關係,並記錄在ContentType表中。

當我們的專案做資料遷移後,會有很多django自帶的表,其中就有django_content_type表,我們可以去看下~~~

ContentType元件應用:

  -- 在model中定義ForeignKey欄位,並關聯到ContentType表,通常這個欄位命名為content-type

  -- 在model中定義PositiveIntergerField欄位, 用來儲存關聯表中的主鍵,通常我們用object_id

  -- 在model中定義GenericForeignKey欄位,傳入上面兩個欄位的名字

  --  方便反向查詢可以定義GenericRelation欄位

建模:

class Appliance(models.Model):
    """
    家用電器表
    id name
    1   冰箱
    2   電視
    3   洗衣機
    """
    name = models.CharField(max_length=64)
    coupons = GenericRelation(to="Coupon")  # 自用於反向查詢 不生成欄位
class Food(models.Model): """ 食物表 id name 1 麵包 2 牛奶 """ name = models.CharField(max_length=32) class Fruit(models.Model): """ 水果表 id name 1 蘋果 2 香蕉 """ name = models.CharField(max_length=32) class Coupon(models.Model):
""" 優惠券表 id name appliance_id food_id fruit_id 1 通用優惠券 null null null 2 冰箱折扣券 1 null null 3 電視折扣券 2 null null 4 蘋果滿減卷 null null 1 我每增加一張表就要多增加一個欄位 """ name = models.CharField(max_length=32) # appliance = models.ForeignKey(to="Appliance", null=True, blank=True) # food = models.ForeignKey(to="Food", null=True, blank=True) # fruit = models.ForeignKey(to="Fruit", null=True, blank=True) # 第一步 去ContentType表跟表繫結關係 content_type = models.ForeignKey(to=ContentType) # 第二步 物件的id object_id = models.PositiveIntegerField() # 第三步 通過外檢關係給表以及物件id繫結關係 得到物件 content_object = GenericForeignKey('content_type', 'object_id')  

使用:

from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.contenttypes.models import ContentType
from .models import Appliance, Coupon
 
# Create your views here.
 
 
class Test(APIView):
 
    def get(self, request):
        # 通過ContentType獲得表名
        content = ContentType.objects.filter(app_label="app01", model="appliance").first()
        # 獲得表model物件 相當於models.Applicance
        model_class = content.model_class()
        ret = model_class.objects.all()
 
        # 為海爾冰箱建立一條優惠記錄
        ice_box = Appliance.objects.filter(id=1).first()
        Coupon.objects.create(name="海爾冰箱折扣券", content_object=ice_box)
 
        # 查詢優惠券id=1綁定了哪個商品
        coupon_obj = Coupon.objects.filter(id=1).first()
        goods_obj = coupon_obj.content_object
        print(goods_obj.name)
 
        # 查詢海爾冰箱的所有優惠券 id=1
        # 我們定義了反向查詢
        results = ice_box.coupons.all()
        print(results[0].name)
 
        # 如果沒定義反向查詢
        content = ContentType.objects.filter(app_label="app01", model="appliance").first()
        result = Coupon.objects.filter(content_type=content, object_id=1).all()
        print(result[0].name)
        return HttpResponse(ret)