contenttypes 是Django內置的一個應用,能夠追蹤項目中全部app和model的對應關係,並記錄在ContentType表中。
1.建立一個項目python
2.數據庫遷移,生成默認表。數據庫
3.存着全部app的名字、表名字。django
每當咱們建立了新的model並執行數據庫遷移後,ContentType表中就會自動新增一條記錄。好比我在應用app01的models.py中建立表class Electrics(models.Model): pass
。從數據庫查看ContentType表,顯示以下:flask
id | app_label | model |
---|---|---|
… | admin, auth等內置應用… | … |
5 | contenttypes | contenttype |
6 | app01 | electrics |
那麼這個表有什麼做用呢?這裏提供一個場景,網上商城購物時,會有各類各樣的優惠券,好比通用優惠券,滿減券,或者是僅限特定品類的優惠券。在數據庫中,能夠經過外鍵將優惠券和不一樣品類的商品表關聯起來:app
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 electric_id food_id cloth_id 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)
food = models.ForeignKey(to='Foods', null=True)
cloth = models.ForeignKey(to='Clothes', null=True)
若是是通用優惠券,那麼全部的ForeignKey爲null,若是僅限某些商品,那麼對應商品ForeignKey記錄該商品的id,不相關的記錄爲null。可是這樣作是有問題的:實際中商品品類繁多,並且極可能還會持續增長,那麼優惠券表中的外鍵將愈來愈多,可是每條記錄僅使用其中的一個或某幾個外鍵字段。ide
contenttypes 應用
經過使用contenttypes 應用中提供的特殊字段GenericForeignKey,咱們能夠很好的解決這個問題。只須要如下三步:post
- 在model中定義ForeignKey字段,並關聯到ContentType表。一般這個字段命名爲「content_type」
- 在model中定義PositiveIntegerField字段,用來存儲關聯表中的主鍵。一般這個字段命名爲「object_id」
- 在model中定義GenericForeignKey字段,傳入上述兩個字段的名字。
爲了更方便查詢商品的優惠券,咱們還能夠在商品類中經過GenericRelation字段定義反向關係。spa
示例代碼:3d
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import 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 Foods(models.Model): name = models.CharField(max_length=32) price=models.IntegerField(default=100) coupons = GenericRelation(to='Coupon') def __str__(self): return self.name class Clothes(models.Model): name = models.CharField(max_length=32) price = models.IntegerField(default=100) coupons = GenericRelation(to='Coupon') def __str__(self): return self.name class bed(models.Model): name = models.CharField(max_length=32) price = models.IntegerField(default=100) coupons = GenericRelation(to='Coupon') class Coupon(models.Model): """ Coupon id name content_type_id object_id_id 1 美的滿減優惠券 9(電器表electrics) 3 2 豬蹄買一送一優惠券 10 2 3 南極被子買200減50優惠券 11 1 """ name = models.CharField(max_length=32) content_type = models.ForeignKey(to=ContentType) # step 1 object_id = models.PositiveIntegerField() # step 2 content_object = GenericForeignKey('content_type', 'object_id') # step 3 def __str__(self): return self.name
注意:ContentType只運用於1對多的關係!!!而且多的那張表中有多個ForeignKey字段。
4.數據化遷移,再給每張表添加數據。code
4.1.衣服表。
4.2.電器表。
4.3.食物表。
4.4.django_content_type表。
5.再加一張表(牀上用品表),數據遷移後,添加幾條數據。
class bed(models.Model): name = models.CharField(max_length=32) coupons = GenericRelation(to='Coupon')
5.1牀上用品表
建立記錄和查詢
from django.shortcuts import render, HttpResponse from app01 import models from django.contrib.contenttypes.models import ContentType def test(request): if request.method == 'GET': # ContentType表對象有model_class() 方法,取到對應model content = ContentType.objects.filter(app_label='app01', model='electrics').first() # 表名小寫 cloth_class = content.model_class() # cloth_class 就至關於models.Electrics res = 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_object print(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,只需定義三個字段就搞定!
建立記錄
關係表的結構
注意:直接用表加,object_id寫不了。
6.用語法給關係表加記錄。
6.1添加方式1:
查看關係表記錄
6.2添加方式2:
查看關係表記錄
代碼:
from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def index(request): """ Coupon id name content_type_id object_id 1 美的滿減優惠券 9(電器表electrics) 3 2 豬蹄買一送一優惠券 10 2 3 南極被子買200減50優惠券 11 1 """ # 建立一個優惠券方式1: # 爲美的冰箱(id=3)建立一條優惠記錄 # s_tv = models.Electrics.objects.filter(id=3).first() # models.Coupon.objects.create(name='美的滿減優惠券', content_object=s_tv) # 建立一個優惠券方式2: # 爲豬蹄(id=2),食物表id爲10, 建立一條優惠記錄。 models.Coupon.objects.create(name='豬蹄買一送一優惠券', content_type_id =10, object_id=2) return HttpResponse("ok")
查詢記錄
7.查詢‘豬蹄買一送一優惠券’對應商品的價格。
from app01 import models coupon = models.Coupon.objects.filter(name="豬蹄買一送一優惠券").first() coupon <Coupon: 豬蹄買一送一優惠券> coupon.content_type <ContentType: foods> coupon.content_type.model 'foods' coupon.object_id 2 coupon.content_type.model_class() <class 'app01.models.Foods'> coupon.content_type.model_class().objects.filter(pk=coupon.object_id) <QuerySet [<Foods: 豬蹄>]> coupon.content_type.model_class().objects.filter(pk=coupon.object_id).first().price coupon.content_object <Foods: 豬蹄> coupon.content_object.price
45
from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def index(request): """ Coupon id name content_type_id object_id 1 美的滿減優惠券 9(電器表electrics) 3 2 豬蹄買一送一優惠券 10 2 3 南極被子買200減50優惠券 11 1 """ ''' #添加優惠券 # 建立一個優惠券方式1: # 爲美的冰箱(id=3)建立一條優惠記錄 # s_tv = models.Electrics.objects.filter(id=3).first() # models.Coupon.objects.create(name='美的滿減優惠券', content_object=s_tv) # 建立一個優惠券方式2: # 爲豬蹄(id=2),食物表id爲10, 建立一條優惠記錄。 models.Coupon.objects.create(name='豬蹄買一送一優惠券', content_type_id =10, object_id=2) ''' # 查詢優惠券 ''' # 查詢‘豬蹄買一送一優惠券’對應商品的價格。 coupon_obj = models.Coupon.objects.filter(id=2).first() prod = coupon_obj.content_object price = coupon_obj.content_object.price print(prod,price) # 豬蹄 45 ''' # 美的冰箱全部的優惠券 return HttpResponse("ok")
8.美的冰箱全部的優惠券
from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def index(request): """ Coupon id name content_type_id object_id 1 美的滿減優惠券 9(電器表electrics) 3 2 豬蹄買一送一優惠券 10 2 3 南極被子買200減50優惠券 11 1 """ ''' #添加優惠券 # 建立一個優惠券方式1: # 爲美的冰箱(id=3)建立一條優惠記錄 # s_tv = models.Electrics.objects.filter(id=3).first() # models.Coupon.objects.create(name='美的滿減優惠券', content_object=s_tv) # 建立一個優惠券方式2: # 爲豬蹄(id=2),食物表id爲10, 建立一條優惠記錄。 models.Coupon.objects.create(name='豬蹄買一送一優惠券', content_type_id =10, object_id=2) ''' # 查詢優惠券 ''' # 查詢‘豬蹄買一送一優惠券’對應商品的價格。 coupon_obj = models.Coupon.objects.filter(id=2).first() prod = coupon_obj.content_object price = coupon_obj.content_object.price print(prod,price) # 豬蹄 45 ''' # 美的冰箱全部的優惠券 meidi=models.Electrics.objects.filter(name="美的冰箱").first() yhqs=meidi.coupons.all() print(yhqs) # <QuerySet [<Coupon: 美的冰箱滿減優惠券>, <Coupon: 美的冰箱7折優惠券>]> return HttpResponse("ok")
路飛學城相似的表關係
course(專題課程) id name id name 1 flasky源碼 degree(學位課程) id name id name 1 python全棧開發 Price strategy(價格策略) id price period course_id degree_id id price period course_id degree_id 1 100 1周 1 2 200 4周 1 3 600 9周 1 OftenQuestion # 問題表 id title course_id degree_id id title course_id degree_id 1 flask怎麼下載 1 2 flask文檔如何去讀 1