zoukankan      html  css  js  c++  java
  • 20,Django contenttypes 应用

    contenttypes 是Django内置的一个应用,可以追踪项目中所有app和model的对应关系,并记录在ContentType表中。

    1.创建一个项目

    2.数据库迁移,生成默认表。

    3.存着所有app的名字、表名字。

    每当我们创建了新的model并执行数据库迁移后,ContentType表中就会自动新增一条记录。比如我在应用app01的models.py中创建表class Electrics(models.Model): pass。从数据库查看ContentType表,显示如下:

    idapp_labelmodel
    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    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字段定义反向关系。

    示例代码:

    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
            1     美的满减优惠券            9(电器表electrics)  3
            2     猪蹄买一送一优惠券        10                    2
            3     南极被子买200减50优惠券   11                    1
        """
        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

    注意:ContentType只运用于1对多的关系!!!并且多的那张表中有多个ForeignKey字段。

    4.数据化迁移,再给每张表添加数据。

    4.1.衣服表。

    4.2.电器表。

    4.3.食物表。

    4.4.django_content_type表。

    5.再加一张表(床上用品表),数据迁移后,添加几条数据。

    class bed(models.Model):
        name = models.CharField(max_length=32)
        coupons = GenericRelation(to='Coupon')

    5.1床上用品表

    创建记录和查询

    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('....')

    总结:

    当一张表和多个表FK关联,并且多个FK中只能选择其中一个或其中n个时,可以利用contenttypes app,只需定义三个字段就搞定!

    创建记录

    关系表的结构

    注意:直接用表加,object_id写不了。

    6.用语法给关系表加记录。

    6.1添加方式1:

    查看关系表记录

    6.2添加方式2:

    查看关系表记录

    代码:

    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from app01 import models
    
    def index(request):
        """
        Coupon
            id    name                      content_type_id       object_id
            1     美的满减优惠券            9(电器表electrics)  3
            2     猪蹄买一送一优惠券        10                    2
            3     南极被子买200减50优惠券   11                    1
        """
        # 创建一个优惠券方式1:
        # 为美的冰箱(id=3)创建一条优惠记录
        # s_tv = models.Electrics.objects.filter(id=3).first()
        # models.Coupon.objects.create(name='美的满减优惠券', content_object=s_tv)
    
        # 创建一个优惠券方式2:
        # 为猪蹄(id=2),食物表id为10, 创建一条优惠记录。
        models.Coupon.objects.create(name='猪蹄买一送一优惠券', content_type_id =10, object_id=2)
    
        return HttpResponse("ok")

    查询记录

    7.查询‘猪蹄买一送一优惠券’对应商品的价格。

    from app01 import models
    coupon = models.Coupon.objects.filter(name="猪蹄买一送一优惠券").first()
    coupon
    <Coupon: 猪蹄买一送一优惠券>
    coupon.content_type
    <ContentType: foods>
    coupon.content_type.model
    'foods'
    
    
    coupon.object_id
    2
    coupon.content_type.model_class()
    <class 'app01.models.Foods'>
    coupon.content_type.model_class().objects.filter(pk=coupon.object_id)
    <QuerySet [<Foods: 猪蹄>]>
    
    
    coupon.content_type.model_class().objects.filter(pk=coupon.object_id).first().price
    coupon.content_object
    <Foods: 猪蹄>
    coupon.content_object.price
    45

    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from app01 import models
    
    def index(request):
        """
        Coupon
            id    name                      content_type_id       object_id
            1     美的满减优惠券            9(电器表electrics)  3
            2     猪蹄买一送一优惠券        10                    2
            3     南极被子买200减50优惠券   11                    1
        """
        '''
        #添加优惠券
        # 创建一个优惠券方式1:
        # 为美的冰箱(id=3)创建一条优惠记录
        # s_tv = models.Electrics.objects.filter(id=3).first()
        # models.Coupon.objects.create(name='美的满减优惠券', content_object=s_tv)
    
        # 创建一个优惠券方式2:
        # 为猪蹄(id=2),食物表id为10, 创建一条优惠记录。
        models.Coupon.objects.create(name='猪蹄买一送一优惠券', content_type_id =10, object_id=2)
        '''
    
        # 查询优惠券
        '''
        # 查询‘猪蹄买一送一优惠券’对应商品的价格。
        coupon_obj = models.Coupon.objects.filter(id=2).first()
        prod = coupon_obj.content_object
        price = coupon_obj.content_object.price
        print(prod,price)  # 猪蹄 45
        '''
        # 美的冰箱所有的优惠券
    
        return HttpResponse("ok")
    View Code

    8.美的冰箱所有的优惠券

    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from app01 import models
    
    def index(request):
        """
        Coupon
            id    name                      content_type_id       object_id
            1     美的满减优惠券            9(电器表electrics)  3
            2     猪蹄买一送一优惠券        10                    2
            3     南极被子买200减50优惠券   11                    1
        """
        '''
        #添加优惠券
        # 创建一个优惠券方式1:
        # 为美的冰箱(id=3)创建一条优惠记录
        # s_tv = models.Electrics.objects.filter(id=3).first()
        # models.Coupon.objects.create(name='美的满减优惠券', content_object=s_tv)
    
        # 创建一个优惠券方式2:
        # 为猪蹄(id=2),食物表id为10, 创建一条优惠记录。
        models.Coupon.objects.create(name='猪蹄买一送一优惠券', content_type_id =10, object_id=2)
        '''
    
        # 查询优惠券
        '''
        # 查询‘猪蹄买一送一优惠券’对应商品的价格。
        coupon_obj = models.Coupon.objects.filter(id=2).first()
        prod = coupon_obj.content_object
        price = coupon_obj.content_object.price
        print(prod,price)  # 猪蹄 45
        '''
    
        # 美的冰箱所有的优惠券
        meidi=models.Electrics.objects.filter(name="美的冰箱").first()
        yhqs=meidi.coupons.all()
        print(yhqs)  # <QuerySet [<Coupon: 美的冰箱满减优惠券>, <Coupon: 美的冰箱7折优惠券>]>
    
        return HttpResponse("ok")
    View Code

    路飞学城类似的表关系

    course(专题课程)
        id
        name
            id    name
            1    flasky源码
    
    degree(学位课程)
        id
        name
            id    name
            1    python全栈开发
    
    Price strategy(价格策略)
        id
        price
        period
        course_id
        degree_id
            id    price    period    course_id  degree_id
            1    100        1周        1
            2    200        4周        1
            3    600        9周        1
    
    
    
    OftenQuestion  # 问题表
        id
        title
        course_id
        degree_id
    
        id    title                course_id    degree_id
        1     flask怎么下载        1
        2     flask文档如何去读    1
    View Code
     
     
     
  • 相关阅读:
    元素绝对定位以后设置了高宽,a标签不能点击的原因总结
    SQL Server 索引结构及其使用(一)[转]
    【转】谈谈网页设计中的字体应用 (1) Font Set
    【转】 谈谈网页设计中的字体应用 (3) 实战应用篇·上
    SQL Server 索引结构及其使用(三)
    SQL Server 索引结构及其使用(二)
    SQL Server的复合索引学习【转载】
    【转】 谈谈网页设计中的字体应用 (4) 实战应用篇·下
    【转】谈谈网页设计中的字体应用 (2) serif 和 sansserif
    SQL Server 索引结构及其使用(四
  • 原文地址:https://www.cnblogs.com/feifeifeisir/p/10105112.html
Copyright © 2011-2022 走看看