2011-05-25 97 views
1

我想在管理中的ManyToMany關係上使用raw_id_fields,並且我希望每個相關對象都顯示在其自己的行上(而不是單個字段中的逗號分隔列表,是默認行爲)。繼在野外發現的例子,好像我應該能夠做到這一點:raw_id_fields和Django中的ManyToMany管理

# models.py 
class Profile(models.Model): 
    ... 
    follows = models.ManyToManyField(User,related_name='followees') 

# admin.py 
class FollowersInline(admin.TabularInline): 
    model = Profile 
    raw_id_fields = ('follows',) 
    extra = 1 

class ProfileAdmin(admin.ModelAdmin): 
    search_fields = ('user__first_name','user__last_name','user__username',) 
    inlines = (FollowersInline,) 

admin.site.register(Profile,ProfileAdmin) 

但生成錯誤:

<class 'bucket.models.Profile'> has no ForeignKey to <class 'bucket.models.Profile'> 

我並不清楚我在做什麼錯在這裏。感謝您的建議。

回答

1

看起來您正在爲您的InlineAdmin 設置錯誤的模型,因爲您定義的追隨者的模型是User而不是Profile

望着docs我說你應該嘗試:

class FollowersInline(admin.TabularInline): 
    model = Profile.follows.through 

class ProfileAdmin(admin.ModelAdmin): 
    .... 
    exclude = ('follows',) 
    inlines = (FollowersInline,) 
+0

感謝阿里,但是這給了我: 'FollowersInline.raw_id_fields' 是指字段「如下'從模型'Profile_follows'中缺少。 下面存在配置文件中的字段。 – shacker 2011-05-25 07:45:42

+0

嗯,可能我並不完全理解你想做的事情:你正在試圖將「追隨者」和「簡介」聯繫起來,對吧?根據我的理解,你應該可以在'InlineAdmin'上省略'raw_id_fields =('follow',)'。然後,您可以使用內聯表單將'Followers'('User')關聯到'Profiles'。 – arie 2011-05-25 07:53:48

+0

追隨者不是一個單獨的模型 - 'follow'是配置文件模型上的m2m字段的名稱。我可以從ProfileAdmin中忽略以下內容,但是當我向ProfileAdmin添加inlines =(FollowersInline,)時,根據是使用'model = Profile'還是'model = Profile.follows.through',我得到了上述兩個錯誤之一。 。謝謝。 – shacker 2011-05-25 16:03:04