转载
https://blog.youkuaiyun.com/Ayhan_huang/article/details/78626957
使用外键关联Foods 表,models中会写上
food_obj = models.ForeignKey(to=’Foods’, null=True)
这是一个字段,在数据库 表中占一列
如果在关联一个Clothes 表
cloth_obj = models.ForeignKey(to=’Clothes’, null=True)
数据表 又会增加一列
null 的作用的 可能只会关联上述两张表的其中一张
如果我们想再增加一张表,又要增加一个字段,数据表增加了一列
这样非常的不好,将上述2个字段 合二为一
content_type = models.ForeignKey(to=ContentType) # step 1
object_id = models.PositiveIntegerField() # step 2
content_object = GenericForeignKey(‘content_type’, ‘object_id’) # step
class Coupon(models.Model):
"""
id name Electrics Foods Clothes
1 通用优惠券 null null null
2 冰箱满减券 2 null null
3 面包狂欢节 null 1 null
"""
name = models.CharField(max_length=32)
electric_obj = models.ForeignKey(to='Electrics', null=True)
food_obj = models.ForeignKey(to='Foods', null=True)
cloth_obj = models.ForeignKey(to='Clothes', null=True)
class Coupon(models.Model):
name = models.CharField(max_length=32)
content_type = models.ForeignKey(to=ContentType) # step 1
object_id = models.PositiveIntegerField() # step 2
content_object = GenericForeignKey('content_type', 'object_id') # step 3
def __str__(self):
return self.name