Django contenttypes 应用
Django contenttypes 应用#
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 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 Electrics Foods Clothes more...
1 通用优惠券 null null null
2 冰箱满减券 2 null null
3 面包狂欢节 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)1234567891011121314151617181920212223242526272829303132333435363738
如果是通用优惠券,那么所有的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 GenericForeignKey
class Electrics(models.Model):
name = models.CharField(max_length=32)
coupons = GenericRelation(to='Coupon') # 用于反向查询,不会生成表字段
def __str__(self):
return self.name
class Foods(models.Model):
name = models.CharField(max_length=32)
coupons = GenericRelation(to='Coupon')
def __str__(self):
return self.name
class Clothes(models.Model):
name = models.CharField(max_length=32)
coupons = GenericRelation(to='Coupon')
def __str__(self):
return self.name
class Coupon(models.Model):
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.name12345678910111213141516171819202122232425262728293031323334353637
创建记录和查询#
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('....')12345678910111213141516171819202122232425262728293031
总结:#
当一张表和多个表FK关联,并且多个FK中只能选择其中一个或其中n个时,可以利用contenttypes app,只需定义三个字段就搞定!
作者: Allen丶W
出处:https://www.cnblogs.com/allen-w/p/9487138.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。
分类:
Django
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端