python - 使用抽象模型定义字段关系

标签 python django django-models

我在尝试测试用抽象模型定义关系几个小时后就投降了,我尝试了多态但没有运气,我也尝试了 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',它会知道它是一个域并返回它 - 这一切都取决于您是否打算允许一个实例拥有Template的多种类型继承。

关于python - 使用抽象模型定义字段关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196992/

相关文章:

python - 调用函数时将列表转换为 *args

python - keras 中不兼容的密集层错误

python - os.walk() python : xml representation of a directory structure, 递归

python - 查找 django 中订单数最多的表现最好的类别列表

python - 在层次结构中显示类别和子类别

python - 如何避免Python中Gtk.Dialog关闭?

python - Django 模型类和自定义属性

python - 模板中的 Django 日期格式 : %B causes "No exception message supplied" error

django - 简单的 jQuery 发布问题(使用 Django)

css - 使用 CSS 的 Django ModelForms 单选按钮