路飞项目-ContentType组件

ContentType组件

    -- 应用 价格策略 常见问题 优惠券
    -- 一张表跟多张表建立外键关系的
    -- 用法
        # 第一步 先生成ForeignKey字段 关联ContentType
        content_type = models.ForeignKey(to=ContentType)
        # 第二步 生成一个IntergerField 字段关联
        object_id = models.PositiveIntegerField()
        # 第三步 生成一个GenericForeignKey 把上面两个字段注册进去
        content_object = GenericForeignKey("content_type", "object_id")
    -- 创建和查询
        # 通过contentType找到OldBoy中所有的信息
        # content = ContentType.objects.filter(app_label="app01", model="oldboy").first()
        # oldboy_model = content.model_class()
        # ret = oldboy_model.objects.all()
        # print(ret)
        # 给Yuan局长加优惠券信息
        yuan_obj = OldBoy.objects.filter(id=2).first()
        Coupon.objects.create(name="苑局1000-750优惠券", content_object=yuan_obj)

        # alex_obj = OldBoy.objects.filter(id=1).first()
        # Coupon.objects.create(name="Alex打折优惠券", content_object=alex_obj)

        # 查询优惠券id=1的关联的商品
        # coupon_obj = Coupon.objects.filter(id=1).first()
        # goods_obj = coupon_obj.content_object
        # print(goods_obj)

        # 查询苑昊的优惠券
        yuan_obj = OldBoy.objects.filter(id=2).first()
        coupon_list = yuan_obj.coupons.all()
        print(coupon_list)
原文地址:https://www.cnblogs.com/benson321/p/9702952.html