日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Django contenttypes 应用

發(fā)布時間:2025/3/17 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django contenttypes 应用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Django contenttypes 應(yīng)用

contenttypes 是Django內(nèi)置的一個應(yīng)用,可以追蹤項目中所有app和model的對應(yīng)關(guān)系,并記錄在ContentType表中。

每當(dāng)我們創(chuàng)建了新的model并執(zhí)行數(shù)據(jù)庫遷移后,ContentType表中就會自動新增一條記錄。比如我在應(yīng)用app01的models.py中創(chuàng)建表class Electrics(models.Model): pass。從數(shù)據(jù)庫查看ContentType表,顯示如下:

idapp_labelmodel
admin, auth等內(nèi)置應(yīng)用…
5contenttypescontenttype
6app01electrics

那么這個表有什么作用呢?這里提供一個場景,網(wǎng)上商城購物時,會有各種各樣的優(yōu)惠券,比如通用優(yōu)惠券,滿減券,或者是僅限特定品類的優(yōu)惠券。在數(shù)據(jù)庫中,可以通過外鍵將優(yōu)惠券和不同品類的商品表關(guān)聯(lián)起來:

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 通用優(yōu)惠券 null null null 2 冰箱滿減券 2 null null3 面包狂歡節(jié) 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)

如果是通用優(yōu)惠券,那么所有的ForeignKey為null,如果僅限某些商品,那么對應(yīng)商品ForeignKey記錄該商品的id,不相關(guān)的記錄為null。但是這樣做是有問題的:實際中商品品類繁多,而且很可能還會持續(xù)增加,那么優(yōu)惠券表中的外鍵將越來越多,但是每條記錄僅使用其中的一個或某幾個外鍵字段。

通過使用contenttypes 應(yīng)用中提供的特殊字段GenericForeignKey,我們可以很好的解決這個問題。只需要以下三步:

  • 在model中定義ForeignKey字段,并關(guān)聯(lián)到ContentType表。通常這個字段命名為“content_type”
  • 在model中定義PositiveIntegerField字段,用來存儲關(guān)聯(lián)表中的主鍵。通常這個字段命名為“object_id”
  • 在model中定義GenericForeignKey字段,傳入上述兩個字段的名字。

為了更方便查詢商品的優(yōu)惠券,我們還可以在商品類中通過GenericRelation字段定義反向關(guān)系。

示例代碼:

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

創(chuàng)建記錄和查詢

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() 方法,取到對應(yīng)modelcontent = ContentType.objects.filter(app_label='app01', model='electrics').first() # 表名小寫cloth_class = content.model_class() # cloth_class 就相當(dāng)于models.Electricsres = cloth_class.objects.all()print(res)# 為三星電視(id=2)創(chuàng)建一條優(yōu)惠記錄s_tv = models.Electrics.objects.filter(id=2).first()models.Coupon.objects.create(name='電視優(yōu)惠券', content_object=s_tv)# 查詢優(yōu)惠券(id=1)綁定了哪些商品coupon_obj = models.Coupon.objects.filter(id=1).first()prod = coupon_obj.content_objectprint(prod)# 查詢?nèi)请娨?id=2)的所有優(yōu)惠券res = s_tv.coupons.all()print(res)# 查詢obj的所有優(yōu)惠券:如果沒有定義反向查詢字段,通過如下方式: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('....')

總結(jié):

當(dāng)一張表和多個表FK關(guān)聯(lián),并且多個FK中只能選擇其中一個或其中n個時,可以利用contenttypes app,只需定義三個字段就搞定!

新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!

總結(jié)

以上是生活随笔為你收集整理的Django contenttypes 应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。