如果一个表跟多个表都有外键关系, 那么就用ContentType
-
model.py
from django.db import models from django.contrib.contenttypes.models import ContentType # GenericRelation 用来反向查询的 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation class PythonBasic(models.Model): course_name = models.CharField(max_length=32, verbose_name="课程名称") # 定义反向查询字段 coupons = GenericRelation(to="Coupon") class Meta: db_table = "db_python_basic" verbose_name = "python课程信息" verbose_name_plural = verbose_name class Oop(models.Model): course_name = models.CharField(max_length=32, verbose_name="课程名称") coupon = GenericRelation(to="Coupon") class Meta: db_table = "db_oop" verbose_name = "面向对象课程信息" verbose_name_plural = verbose_name class Coupon(models.Model): coupon_name = models.CharField(max_length=32, verbose_name="优惠卷名称") # 关联到ContentType的外键 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # 关联表的数据所对应表的主键id object_id = models.PositiveIntegerField() # 这个字段在数据库不存在, 这个字段帮助我们管理对应关系的 content_object = GenericForeignKey("content_type", "object_id") class Meta: db_table = "db_coupon" verbose_name = "优惠卷信息" verbose_name_plural = verbose_name
-
url.py
from django.urls import re_path from .views import CourseView urlpatterns = [ re_path(r"^course/$", CourseView.as_view()) ]
-
views.py
from django.shortcuts import HttpResponse from django.views import View from django.contrib.contenttypes.models import ContentType from .models import ( PythonBasic, Oop, Coupon ) from .app_serializers import BookSerializer class CourseView(View): def get(self, request): # 获取表名 # pb = ContentType.objects.get(app_label="serializer", model="pythonbasic") # 获取表对象 # pb_model = pb.model_class() # 获取去表里的第一条数据的对象 # pb_obj = pb_model.objects.get(id=1) # print(pb_obj.course_name) # 获取当前对象 object_id = PythonBasic.objects.get(id=3) # 把当前对象插入到这个表中 要操作这个表只能用content_object字段来操作 因为content_object是关系字段 Coupon.objects.create(coupon_name="Python基础通关优惠卷", content_object=object_id) return HttpResponse("ok")
-
效果图