- 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")
- 效果圖
Django的ContentType