首页 > 其他 > 详细

Django中contenttype的应用

时间:2017-11-24 23:21:26      阅读:267      评论:0      收藏:0      [点我收藏+]

content_type表将app名称与其中的表的关系进行保存

技术分享图片

 通过下边的示例来理解content_type的具体应用:

models:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
# Create your models here.
class Food(models.Model):
    name = models.CharField(max_length=32)
    coupon = GenericRelation("Coupon")
class Cloth(models.Model):
    name = models.CharField(max_length=32)
    coupon = GenericRelation("Coupon")
class Coupon(models.Model):
    """
    id      food_id     cloth_id  ……
    1         null        null
    2           1         null
    """
    name = models.CharField("活动名称",max_length=64)
    brief = models.TextField(blank=True,null=True,verbose_name="优惠券介绍")
    content_type = models.ForeignKey(ContentType,blank=True,null=True) # 代表哪个app下的哪张表
    object_id = models.PositiveIntegerField("绑定商品",blank=True,null=True) # 代表哪张表中的对象id
    content_obj = GenericForeignKey("content_type","object_id") #不会生成额外的列

view:

from django.shortcuts import render,HttpResponse
from . import models

def test(request):

    # c = models.Cloth.objects.get(id=1)
    # models.Coupon.objects.create(name=‘优惠券‘,brief=‘100减10‘,content_obj=c) 

    # c = models.Cloth.objects.get(id=1)
    # models.Coupon.objects.create(name=‘优惠券‘,brief=‘200减30‘,content_obj=c)

    # 查看优惠券绑定的所有课程
    # c = models.Coupon.objects.get(id=1)
    # print(c.content_obj)

    # 查看该商品下的所有优惠券
    c = models.Cloth.objects.get(id=1)
    print(c.coupon.all())
    c2 = models.Cloth.objects.values(name,coupon__brief)
    print(c2)

    return HttpResponse(ok)

 

Django中contenttype的应用

原文:http://www.cnblogs.com/c491873412/p/7892585.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!