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')

 

posted @ 2018-12-11 20:26  被嫌弃的胖子  阅读(244)  评论(0编辑  收藏  举报