2016-09-13 38 views
2

我試圖使用通用的關係,我的模型是這樣的:無法解析關鍵字「CONTENT_TYPE」到現場

class Post(models.Model): 
    # Identifiers 
    user = models.ForeignKey(User, unique=False, related_name = 'posts') 
    # Resource 
    resource_type = models.ForeignKey(ContentType) 
    resource_id = models.PositiveIntegerField() 
    resource = GenericForeignKey('resource_type', 'resource_id') 

    # Other 
    date_created = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True) 

    class Meta: 
     unique_together = ('resource_type', 'resource_id',) 

但是,當我的資源我試圖讓Post對象,使用'SomeResource.posts '發生以下異常:

無法將關鍵字'content_type'解析爲字段。選項包括: DATE_CREATED,ID,資源,RESOURCE_ID,RESOURCE_TYPE, resource_type_id,用戶邀請,USER_ID

爲什麼找content_type當我明確地將其命名爲resource_typeGenericForeignKey

回答

0

你有使用'資源'而不是'content'/'object'的具體原因嗎?

如果沒有,我會建議更改與這樣的一般關係的所有3條線(以及元):

content_type = models.ForeignKey(ContentType) 
object_id = models.PositiveIntegerField() 
content = GenericForeignKey('content_type', 'object_id') 

我始終堅持對通用關係這些字段名稱(基於the documentation ),儘管文檔中提到可以重命名'content_type'和'object_id'(也許只有'content'必須保持不變......)。我在Django中不夠好解釋爲什麼這個行爲。

希望這是可行的,適用於你的項目

+0

我想改變他們的可讀性和一致性,因爲我覺得默認的命名是有點笨重。 –

+0

這裏[鏈接](http://stackoverflow.com/questions/18239030/django-generic-relations-error-cannot-resolve-keyword-content-object-into-fi)你可能有一個答案,如果你的問題是過濾對象...對不起,我忍不住要更多 –

+0

沒有抱歉,我的問題是沒有過濾。這是檢索通用對象。 –

1

我沒有在文檔看到它的任何地方的權利,但如果你看看來源爲GenericRelation有關鍵字content_type_field當你創建object_id_field 。因此,如果您將關係創建爲GenericRelation(object_id_field='resource_id', content_type_field='resource_type')那麼它應該查找適當的字段。

我發現這是特別有必要的,如果你在一個模型中有多個GenericForeignKey's,因此不能使用默認名稱。

你可以看到源1.11位置:https://github.com/django/django/blob/stable/1.11.x/django/contrib/contenttypes/fields.py#L291

相關問題