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‘)
时间: 2024-10-07 16:06:29