from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation,GenericForeignKey class SuperCourse(models.Model): name = models.CharField(max_length=32,verbose_name="超级课名") course_policy = GenericRelation(‘CoursePolicy‘) class NormalCourse(models.Model): name = models.CharField(max_length=32,verbose_name=‘普通课名‘) course_policy = GenericRelation(‘CoursePolicy‘) class CoursePolicy(models.Model): price = models.IntegerField(verbose_name="价格") period = models.IntegerField(verbose_name="周期") object_id = models.IntegerField(verbose_name="课程id") table_name = models.ForeignKey(ContentType,verbose_name="关键在ContentType表里面的表名") # obj = GenericForeignKey(‘table_name‘,"object_id") obj = GenericForeignKey(ct_field=table_name,fk_field=object_id)
Django-Content-type用法