zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    Java 访问标识符
    Java 类变量与实例变量的区别
    Java 变量
    python install sublime安装
    Failed to resolve com.android.support:support-annotations 26.0.1
    Git的使用及托管代码到GitHub
    Recyclerview点击事件,更新item的UI+更新Recyclerview外的控件
    第一次android混淆实战
    android计算屏幕dp
    显示当前日期时间
  • 原文地址:https://www.cnblogs.com/qq849784670/p/10104962.html
Copyright © 2011-2022 走看看