Django學習之django自帶的contentType表 GenericRelation GenericForeignKey


Django學習之django自帶的contentType表

 

    通過django的contentType表來搞定一個表里面有多個外鍵的簡單處理: 摘自:https://blog.csdn.net/aaronthon/article/details/81714496

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

    models.py文件的表結構寫好后,通過makemigrations和migrate兩條命令遷移數據后,在數據庫中會自動生成一個django_content_type表,比如我們有在models.py中寫了這么幾張表:

復制代碼
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字段定義反向關系。  

  示例代碼:models.py文件:

復制代碼
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
              美的滿減優惠券                    9(電器表electrics)   3
              豬蹄買一送一優惠券                10                    2
              南極被子買200減50優惠券           11                    1
    """
    name = models.CharField(max_length=32)

    content_type = models.ForeignKey(to=ContentType,on_delete=models.CASCADE) # step 1 既然沒有直接和關聯表進行外鍵關系,我們通過這一步先找到關聯表
    object_id = models.PositiveIntegerField() # step 2  #存的是關聯的那個表的對應的那條記錄的id
    content_object = GenericForeignKey('content_type', 'object_id') # step 3  對象.content_object直接就拿到了這個優惠券對象關聯的那個商品記錄對象。

    def __str__(self):
        return self.name
復制代碼

 

  注意:ContentType只運用於1對多的關系!!!並且多的那張表中有多個ForeignKey字段。  

  數據化遷移,再給每張表添加數據

  衣服表,電器表,床上用品表,美食表

  添加完之后,數據遷移,python manage.py makemigrations 和 python manage.py migrate

復制代碼
創建記錄和查詢

from django.shortcuts import render, HttpResponse
from api 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='api', 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)
復制代碼

 

  

  總結:  當一張表和多個表FK關聯,並且多個FK中只能選擇其中一個或其中n個時,可以利用contenttypes app,只需定義三個字段就搞定!

   創建記錄

    關系表的結構

     

 

   用語法給關系表加記錄。

  添加方式1:

     

    

     

  接下來用postmen來發送請求

     

 

  然后代金券表數據就添加完成了

     

 

  添加方式2:

     

 

  通過postmen發送請求結果

     

 

  查詢記錄

  查詢name="電商1代金券"的代金券信息

     

    

 

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM