【Django】ContentType组件
目录
"@ 那么,我们就要设计优惠券,优惠券都有什么类型呢?满减的、折扣的、立减的、等等等... 我们对应着活动类型,对某类商品设计优惠卷,比如: 所以,我们一顺手,表结构就出来了: from django.db import models is_true = {'null': True,'blank': True} # 家用电器表 class Appliance(models.Model): """ id name 1 冰箱 2 电视 3 洗衣机 """ name = models.CharField(max_length=64) # 食品表 class Food(models.Model): """ id name 1 面包 2 牛掰 """ name = models.CharField(max_length=64) # 水果表 class Fruit(models.Model): """ id name 1 苹果 2 香蕉 """ name = models.CharField(max_length=64) # class ... # 优惠卷表 class Coupon(models.Model): """ id title appliance_id food_id fruit_id 1 通用优惠卷 null null null 2 冰箱折扣券 1 null null 3 电视折扣券 2 null null 4 苹果满减卷 null null 1 """ title = models.CharField(max_length=64) appliance = models.ForeignKey(to='Appliance',**is_true) food = models.ForeignKey(to='Food',**is_true) fruit = models.ForeignKey(to='Fruit',**is_true) # ... # 实际上我们的商品种类会特别多,导致我们这张表的外键也越来越多 殊不知,我们的大Django早就为我们提供了更高明的用法—— 理解
当我们的项目做数据迁移后,会在数据库中生成一些Django自带的表,其中就包含 我们先来看看这张表: 再来看看这张表内默认的数据: 可见,自动就建立了所有APP与其数据表的对应关系. *** 表结构步骤
好,根据开篇的表结构示例以及如上的步骤,我们的新表结构又出来了: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation # 家用电器表 class Appliance(models.Model): name = models.CharField(max_length=64) # 4. 为了方便反向查询,可在被外键表中定义GenericRelation字段并指向创建外键的表 coupons = GenericRelation(to='Coupon') # 食物表 class Food(models.Model): name = models.CharField(max_length=64) # 水果表 class Fruit(models.Model): name = models.CharField(max_length=64) # 优惠卷表 class Coupon(models.Model): title = models.CharField(max_length=64) # 1. 在model中定义ForeignKey字段,并关联到ContentType表 content_type = models.ForeignKey(to=ContentType) # 这里就不要加引号了 # 2. 在model中定义PositiveIntergerField字段,用来存储步骤一中被外键的表中的主键 object_id = models.PositiveIntegerField() # 3. 在model中定义GenericForeignKey字段,传入上面两个字段的名字. content_object = GenericForeignKey('content_type','object_id') 数据迁移后, 使用
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |