Django ContentType组件
1 class TestView(APIView): 2 def get(self, request): 3 # 找到表id以及表对象 4 # content_type_obj = ContentType.objects.filter(app_label="Demo", model="food").first() 5 # print(type(content_type_obj)) 6 # model_class = content_type_obj.model_class() 7 # print(model_class) 8 # print(content_type_obj.id) 9 # 给酱香饼创建优惠券 10 # food_obj = Food.objects.filter(id=1).first() 11 # Coupon.objects.create(title="酱香饼买一送王鸥", content_object=food_obj) 12 # 给黑美人加优惠券 13 # fruit_obj = Fruit.objects.get(id=2) 14 # Coupon.objects.create(title="黑美人2折", content_type_id=9, object_id=2) 15 # Coupon.objects.create(title='鸡蛋饼买一送er',content_type_id=8,object_id=2) 16 # 查询优惠券绑定对象 17 # coupon_obj = Coupon.objects.filter(id=8).first() 18 # print(coupon_obj.content_object.name) 19 # 查某个对象的优惠券 20 food_obj = Food.objects.filter(id=1).first() 21 print(food_obj.coupons.all()) 22 23 # food_obj = Fruit.objects.filter(id=2).first() 24 coupon_obj = food_obj.coupons.all() 25 for coupon in coupon_obj: 26 print(coupon.title) 27 return HttpResponse("ok")
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation # Create your models here. class Food(models.Model): """ id name 1 酱香饼 2 鸡蛋饼 3 水煎包 """ name = models.CharField(max_length=32) # 不生成字段只用于反向查询 coupons = GenericRelation(to="Coupon") class Fruit(models.Model): """ id name 1 红心蜜柚 2 黑美人西瓜 """ name = models.CharField(max_length=32) coupons = GenericRelation(to="Coupon") class Coupon(models.Model): """ id title food_id fruit_id .......... 1 酱香饼买一送一 1 null 2 黑美人西瓜2折 null 2 id title table_id object_id 1 酱香饼买一送一 1 1 2 黑美人西瓜2折 2 2 """ title = models.CharField(max_length=32) # 第一版设计 # food = models.ForeignKey(to="Food") # fruit = models.ForeignKey(to="Fruit") # 第二版设计 # table = models.ForeignKey(to="MyTables") # object_id = models.IntegerField() # 第三版 用django自带的ContentType表 content_type = models.ForeignKey(to=ContentType) object_id = models.IntegerField() # 不会生成字段 只用于关联到对象的 content_object = GenericForeignKey("content_type", "object_id")优质内容筛选与推荐>>