Django_ContentType

ContentType 的本质就是保存 app 和model 表的对应关系

可以通过app名称和 model表的名称来获取对应的表对象

def page1(request):
    # 显示的是 ContentType自己的对象,只是看起来是字符串
    content = ContentType.objects.get(app_label='app01', model='goods')
    # 通过 model_class() 来获取这个model对象
    model_class = content.model_class()
    # 打印这个表的所有字段信息
    print(model_class.objects.all())
    return HttpResponse('...')

ContentType 的应用场景,比如商品跟优惠券的关联关系,比如说通用优惠券可以给各种的类型的商品使用.

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation


# Create your models here.


class Goods(models.Model):
    # 商品表
    title = models.CharField(max_length=128)
    price = models.FloatField(max_length=7)
    # 如果想从商品反查优惠券信息
    coupons = GenericRelation(to='Coupon')


class Service(models.Model):
    title = models.CharField(max_length=128)
    price = models.FloatField(max_length=7)


class Coupon(models.Model):
    # 优惠券表
    name = models.CharField(max_length=256)
    brief = models.TextField()
    # 管理ContentType数据中的那张表
    content_type = models.ForeignKey(ContentType)
    # 关联上面表的具体那个条数据的ID值
    obj_id = models.PositiveIntegerField()
    # 通过优惠券反查数据(ContentType反查)
    content_obj = GenericForeignKey('content_type', 'obj_id')

posted @ 2017-12-13 13:54  neuropathy_ldsly  阅读(60)  评论(0)    收藏  举报