• django-ContentType的简单使用


    ContentType

      一般我们有多张表同时外键关联同一张表的时候,可以考虑使用ContentType

    models.py

     1 from django.db import models
     2 from django.contrib.contenttypes.models import ContentType # django自己生成的表,里面存储着每一个app和它下面的表关系
     3 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
     4 
     5 
     6 class PythonBasic(models.Model):
     7     course_name = models.CharField(max_length=32)
     8     coupons = GenericRelation(to='Coupon') ##相当于foreignkey
     9 
    10 
    11 class Oop(models.Model):
    12     course_name = models.CharField(max_length=32)
    13     coupons = GenericRelation(to='Coupon') ##相当于foreignkey
    14 
    15 
    16 class Coupon(models.Model):
    17     coupon_name = models.CharField(max_length=32)
    18     content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) ##
    19     object_id = models.PositiveIntegerField() ##
    20 
    21     content_object = GenericForeignKey("content_type", "object_id") ## 在表中不会真的生成这个字段,但是对应关系是靠它实现的

    views.py

     1 class ContentTypeView(View):
     2 
     3     def get(self, request):
     4         # 获取表名
     5         # pb = ContentType.objects.filter(app_label='app01', model='pythonbasic').first()
     6         # print(pb.model_class()) # <class 'app01.models.PythonBasic'>
     7         # print(pb.model_class().objects.all()) # <QuerySet [<PythonBasic: PythonBasic object (1)>, <PythonBasic: PythonBasic object (2)>, <PythonBasic: PythonBasic object (3)>]>
     8 
     9         # obj = PythonBasic.objects.get(id=3)
    10         obj = Oop.objects.get(id=2)
    11         # Coupon.objects.create(coupon_name="Python基础通关", content_object=obj)
    12         print(obj.coupons.all())
    13 
    14         return HttpResponse('ok')
  • 相关阅读:
    “终身幼儿园”:学习是一个创造的过程
    我对ERP实质的理解(陈启申)
    Java学习记录1java并发编程之synchronized初学
    谈谈你对Spring的理解
    java中的==与equals的区别
    Windows下编译安装perl Module
    win系统用virtualBox安装Ubuntu虚拟机,如何共享数据
    Windows下emacsw3m设置代理
    自我介绍
    document 对象
  • 原文地址:https://www.cnblogs.com/qq849784670/p/10104962.html
Copyright © 2020-2023  润新知