问题
如何在一张表上对多个表进行外键关联
from django.db import models
class Appliance(models.Model):
"""
家用电器表
id name
1 冰箱
2 电视
3 洗衣机
"""
name = models.CharField(max_length=64)
class Food(models.Model):
"""
食物表
id name
1 面包
2 牛奶
"""
name = models.CharField(max_length=32)
class Fruit(models.Model):
"""
水果表
id name
1 苹果
2 香蕉
"""
name = models.CharField(max_length=32)
class Coupon(models.Model):
"""
优惠券表
id name appliance_id food_id fruit_id
1 通用优惠券 null null null
2 冰箱折扣券 1 null null
3 电视折扣券 2 null null
4 苹果满减卷 null null 1
"""
name = models.CharField(max_length=32)
appliance = models.ForeignKey(to="Appliance", null=True, blank=True)
food = models.ForeignKey(to="Food", null=True, blank=True)
fruit = models.ForeignKey(to="Fruit", null=True, blank=True)
注意
1.每增加一张表就需要多增加一个字段,
定义
当一张表要跟多张表进行外键关联的时候,我们可以使用Django提供的ContentType 组件
ContentTypes是Django内置的一个组件,可以追踪项目中所有app和model的对应关系,并记录在ContentType表中
app1/models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
class Food(models.Model):
"""
id title
1 面包
2 牛奶
"""
title = models.CharField(max_length=32)
coupons = GenericRelation(to="Coupon")
class Fruit(models.Model):
"""
id title
1 苹果
2 香蕉
"""
title = models.CharField(max_length=32)
class Coupon(models.Model):
title = models.CharField(max_length=32)
content_type = models.ForeignKey(to=ContentType, on_delete=None)
object_id = models.IntegerField()
content_object = GenericForeignKey("content_type", "object_id")
app1\view.py
class DemoView(APIView):
def get(self, request):
content = ContentType.objects.filter(app_label="app1", model="food").first()
model_class = content.model_class()
ret = model_class.objects.all()
print(ret)
food_obj = Food.objects.filter(id=1).first()
Coupon.objects.create(title="面包九五折", content_type_id=8, object_id=1)
Coupon.objects.create(title="双十一面包九折促销", content_object=food_obj)
coupon_obj = Coupon.objects.filter(id=1).first()
content_obj = coupon_obj.content_object
print(content_obj.title)
coupons = food_obj.coupons.all()
print(coupons[0].title)
content = ContentType.objects.filter(app_label="app1", model="food").first()
result = Coupon.objects.filter(content_type=content, object_id=1).all()
print(result[0].name)
return Response("ContentType测试")
|