http://python.usyiyi.cn/translate/django_182/ref/contrib/contenttypes.html#django.contrib.contenttypes.models.ContentType
models.py
from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType # Create your models here. class DegreeCourse(models.Model): """学位课程 ID 名称 1 学位课1 2 学位课2 """ name = models.CharField(max_length=128, unique=True) x1 = GenericRelation("Coupon") class Course(models.Model): """课程 ID 名称 1 普通课1 2 普通课2 """ name = models.CharField(max_length=128, unique=True) class Coupon(models.Model): """优惠券生成规则 ID 优惠券名称 A FK B.FK c.FK 1 通用 null null 2 满100-10 8 1 3 满200-30 8 2 4 满200-30 9 1 ID 优惠券名称 content_type_id(表) object_id(表中数据ID) 1 通用 null null 2 满100-10 8 1 3 满200-30 8 2 4 满200-30 9 1 总结: """ name = models.CharField(max_length=64, verbose_name="活动名称") brief = models.TextField(blank=True, null=True, verbose_name="优惠券介绍") # 那个表? content_type = models.ForeignKey(ContentType, blank=True, null=True) # 对象ID object_id = models.PositiveIntegerField("绑定课程", blank=True, null=True, help_text="可以把优惠券跟课程绑定") content_object = GenericForeignKey('content_type', 'object_id')
views.py
from django.shortcuts import render,HttpResponse from django.contrib.contenttypes.models import ContentType from . import models def test(request): # models.UserInfo.objects.filter() # content = ContentType.objects.get(app_label='app01',model='userinfo') # model_class = content.model_class() # print(model_class.objects.all()) # 给学位课1或普通课创建优惠券 # d1 = models.DegreeCourse.objects.get(id=1) # models.Coupon.objects.create(name='优惠券', brief='200-30', content_object=d1) # d1 = models.Course.objects.get(id=1) # models.Coupon.objects.create(name='优惠券', brief='100-90', content_object=d1) # 当前优惠券,绑定的课程? obj = models.Coupon.objects.get(id=1) # print(obj.content_object) # 当前课程,都有哪些优惠券? # obj = models.DegreeCourse.objects.get(id=1) # print(obj.x1.all()) # v = models.DegreeCourse.objects.values('name','x1__brief') # print(v) return HttpResponse('...')