定义一个对象和许多其他类型对象之间关系的一种方法是使用
GenericForeignKey
以及
ContentType
framework
. 我想你会找一个
Product
有一些更具体的相关对象,如
Jacket
. 它可能看起来像这样:
class Product(models.Model):
price = models.FloatField()
description = models.TextField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
details = generic.GenericForeignKey('content_type', 'object_id')
class Jacket(models.Model):
size = models.PositiveIntegerField()
color = models.CharField(max_length=25)
这允许您定义与
夹克
可以与您的产品关联。
jacket = Jacket(size=69, color="pink")
jacket.save()
prod = Product(price=0.99)
prod.details = jacket # It's like magic!
prod.save()
这确实创造了创建大量模型的额外工作,但它也允许您对存储的数据和存储方式非常有创意。