1. 程式人生 > >20,Django contenttypes 應用

20,Django contenttypes 應用

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

1.建立一個專案

 

2.資料庫遷移,生成預設表。

 

3.存著所有app的名字、表名字。

每當我們建立了新的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 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。但是這樣做是有問題的:實際中商品品類繁多,而且很可能還會持續增加,那麼優惠券表中的外來鍵將越來越多,但是每條記錄僅使用其中的一個或某幾個外來鍵欄位。

contenttypes 應用

通過使用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,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.資料化遷移,再給每張表新增資料。

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")
View Code

 

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")
View Code

 

路飛學城類似的表關係

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
View Code

 

     

1.建立一個專案

 

2.資料庫遷移,生成預設表。

 

3.存著所有app的名字、表名字。

每當我們建立了新的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 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。但是這樣做是有問題的:實際中商品品類繁多,而且很可能還會持續增加,那麼優惠券表中的外來鍵將越來越多,但是每條記錄僅使用其中的一個或某幾個外來鍵欄位。

contenttypes 應用

通過使用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,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.資料化遷移,再給每張表新增資料。

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")
View Code

 

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")
View Code

 

路飛學城類似的表關係

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
View Code