content-type 组件

content-type初识

    • 什么是content-type

      • ContentType是Django的内置的一个应用,能够追踪项目中全部的APP和model的对应关系,并记录在ContentType表中。
      • 当咱们的项目作数据迁移后,会有不少django自带的表,其中就有django_content_type表
    • content-type 组件的应用

      • 在model中定义ForeignKey字段,并关联到ContentType表,一般这个字段命名为content-type
      • 在model中定义PositiveIntergerField字段, 用来存储关联表中的主键,一般咱们用object_id
      • 在model中定义GenericForeignKey字段,传入上面两个字段的名字
      • 方便反向查询能够定义GenericRelation字段

 

 

content-type 实践应用

 

  需求:数据库

    先提供一个场景,网上商城购物时,会有各类各样的优惠券,好比通用优惠券,满减券,或者是仅限特定品类的优惠券。咱们以往的方式是:在数据库中,能够经过外键将 优惠券和不一样品类的商品表关联起来:django

  

  
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)
初始关系表创建

  将全部的商品都关联到Coupon这张表中,若是是通用优惠券,那么全部的ForeignKey对应字段的值为null,若是仅限某些商品,那么对应商品ForeignKey记录该商品的id,不相关的记录为null。app

  

  可是这样作是有问题的:ide

  1. 实际中商品品类繁多,并且极可能还会持续增长,那么优惠券表中的外键将愈来愈多,这样咱们就要频繁的修改表
  2. 每条记录仅使用其中的一个或某几个外键字段,这样就会形成表空间的浪费。

  

  解决方法:spa

    经过使用contenttypes 应用中提供的特殊字段GenericForeignKey,咱们能够很好的解决这个问题。只须要如下三步:code

    • 在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.name
models.py
    
 1 from django.shortcuts import render, HttpResponse
 2 from app01 import models
 3 from django.contrib.contenttypes.models import ContentType
 4  
 5  
 6 def test(request):
 7     if request.method == 'GET':
 8         # ContentType表对象有model_class() 方法,取到对应model
 9         content = ContentType.objects.filter(app_label='app01', model='electrics').first()  # 表名小写
10         cloth_class = content.model_class() # cloth_class 就至关于models.Electrics
11         res = cloth_class.objects.all()
12         print(res)
13  
14         # 为三星电视(id=2)建立一条优惠记录
15         s_tv = models.Electrics.objects.filter(id=2).first()
16         models.Coupon.objects.create(name='电视优惠券', content_object=s_tv)
17  
18         # 查询优惠券(id=1)绑定了哪些商品
19         coupon_obj = models.Coupon.objects.filter(id=1).first()
20         prod = coupon_obj.content_object
21         print(prod)
22  
23         # 查询三星电视(id=2)的全部优惠券
24         res = s_tv.coupons.all()
25         print(res)
26  
27         # 查询obj的全部优惠券:若是没有定义反向查询字段,经过以下方式:
28         content = ContentType.objects.filter(app_label='app01', model='model_name').first()
29         res = models.OftenAskedQuestion.objects.filter(content_type=content, object_id=obj.pk).all()
30  
31         return HttpResponse('....')
views.py

  

  总结:blog

    当一张表和多个表FK关联,而且多个FK中只能选择其中一个或其中n个时,能够利用contenttypes app,只需定义三个字段就搞定!经常使用的场景:一个商品的多种优惠券,一门课程按照周期的多种价格、一门课程各自的常见问题等等。it

相关文章
相关标签/搜索