contenttypes 是Django內置的一個應用,可以追蹤項目中所有app和model的對應關系,并記錄在ContentType表中。
每當我們創建了新的model并執行數據庫遷移后,ContentType表中就會自動新增一條記錄。比如我在應用app01的models.py中創建表class Electrics(models.Model): pass
。從數據庫查看ContentType表,顯示如下:
id | app_label | model |
---|---|---|
… | admin, auth等內置應用… | … |
5 | contenttypes | contenttype |
6 | app01 | electrics |
那么這個表有什么作用呢?這里提供一個場景,網上商城購物時,會有各種各樣的優惠券,比如通用優惠券,滿減券,或者是僅限特定品類的優惠券。在數據庫中,可以通過外鍵將優惠券和不同品類的商品表關聯起來:
from django.db import modelsclass Electrics(models.Model):"""id name1 日立冰箱2 三星電視3 小天鵝洗衣機"""name = models.CharField(max_length=32)class Foods(models.Model):"""id name1 面包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 null3 面包狂歡節 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字段定義反向關系。
示例代碼:
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKeyclass Electrics(models.Model):name = models.CharField(max_length=32)coupons = GenericRelation(to='Coupon') # 用于反向查詢,不會生成表字段def __str__(self):return self.nameclass Foods(models.Model):name = models.CharField(max_length=32)coupons = GenericRelation(to='Coupon')def __str__(self):return self.nameclass Clothes(models.Model):name = models.CharField(max_length=32)coupons = GenericRelation(to='Coupon')def __str__(self):return self.nameclass Coupon(models.Model):name = models.CharField(max_length=32)content_type = models.ForeignKey(to=ContentType) # step 1object_id = models.PositiveIntegerField() # step 2content_object = GenericForeignKey('content_type', 'object_id') # step 3def __str__(self):return self.name
創建記錄和查詢
from django.shortcuts import render, HttpResponse from app01 import models from django.contrib.contenttypes.models import ContentTypedef test(request):if request.method == 'GET':# ContentType表對象有model_class() 方法,取到對應modelcontent = ContentType.objects.filter(app_label='app01', model='electrics').first() # 表名小寫cloth_class = content.model_class() # cloth_class 就相當于models.Electricsres = cloth_class.objects.all()print(res)# 為三星電視(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_objectprint(prod)# 查詢三星電視(id=2)的所有優惠券res = s_tv.coupons.all()print(res)# 查詢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()return HttpResponse('....')
總結:
當一張表和多個表FK關聯,并且多個FK中只能選擇其中一個或其中n個時,可以利用contenttypes app,只需定義三個字段就搞定!