2016-10-22 68 views
2

我剛剛投降數小時後試圖測試定義與抽象模型的關係,我嘗試多態但沒有運氣,我也試過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,我不知道該怎麼跟我的「域」模型,以及如何修改它做的,你知道我得到下面的誤差而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'. 

回答

2

好吧,簡單的答案是「你不能解決你在做什麼」 - 你不能有af在不真實的東西上輸入關鍵字段(TemplateField爲抽象意味着它不會生成)。

我認爲問題是,TemplateField 是抽象的。 Django很好地處理了模型的繼承,這意味着你有額外的Db表,但它會工作得很好。

您可能會考慮向TemplateField添加更多功能,以便您瞭解「模板字段是什麼類型」,即如果您嘗試加載模板字段「3」,它知道它的域並將其返回 - 這一切都取決於您是否打算允許一個實例具有Template的多個類型繼承。

相關問題