django-ContentType的簡單使用
阿新 • • 發佈:2018-12-11
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 classPythonBasic(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 16class 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')