我在几个小时后投降了,试图测试定义与抽象模型的关系,我尝试了多态但没有运气,我也尝试了 GenericForeignKey .. 也没有运气,这是我的小代码
class Attribute(models.Model):
name = models.CharField(max_length=50)
class TemplateField(models.Model):
name = models.CharField(null=True,blank=True,max_length=30)
attributes = models.ManyToManyField(Attribute, through='AttributeValue')
class Meta:
abstract = True
class Domain(TemplateField):
name = models.CharField(max_length=33)
class AttributeValue(models.Model):
templatefield = models.ForeignKey(TemplateField)
attribute = models.ForeignKey(Attribute)
value = models.CharField(max_length=50)
当我尝试 GenericForeignKey 时,我不确定如何处理我的“域”模型以及如何修改它,正如您所知,我收到以下错误 [while makemigrate]:
wiki.AttributeValue.templatefield: (fields.E300) Field defines a relation with model 'TemplateField', which is either not installed, or is abstract.
wiki.AttributeValue.templatefield: (fields.E307) The field wiki.AttributeValue.templatefield was declared with a lazy reference to 'wiki.templatefield', but app 'wiki' doesn't provide model 'templatefield'.
wiki.AttributeValue: (fields.E336) The model is used as an intermediate model by 'wiki.Domain.attributes', but it does not have a foreign key to 'Domain' or 'Attribute'.
请您参考如下方法:
好吧,简单的答案是“你不能修复你正在做的事情”——你不能在不真实的东西上有一个外键字段(TemplateField 是抽象的意味着它不会被生成).
我认为问题是,TemplateField 必须是抽象的。 Django 非常好地处理模型的继承,这确实意味着您有额外的 Db 表,但它会“很好”地工作。
您可能会考虑向 TemplateField 添加更多功能,以便您了解“哪种模板字段”,即如果您尝试加载 Templatefield“3”,它会知道它的域并返回它 - 这完全取决于您是否打算这样做允许一个实例具有多种类型的模板继承。
