2015-11-16 41 views
-1

我的Django管理員的每個用戶都關聯了許多配置文件。我想在用戶表中顯示一列,其中列出了與每個用戶關聯的配置文件數。我怎樣才能做到這一點?添加一列到Django UserAdmin界面顯示ForeignKey關係中的計數?

您可以在這裏看到Profile模型的代碼:http://codepad.org/9yLet9el

這是我試過的。 admin.py的相關部分是:

def profile_count(self, user): 
    return user.profiles.count() 

class MyUserAdmin(admin.ModelAdmin): 
    list_display = UserAdmin.list_display + 'profile_count' 

admin.site.unregister(User) 
admin.site.register(User, MyUserAdmin) 

但由於某種原因,用戶管理表保持不變。我究竟做錯了什麼?謝謝。

+0

此外,窺視模型和ModelAdmin將是一個巨大的幫助。 –

+0

@LegoStormtroopr我試着定義'UserAdmin',就像[這個答案](http://stackoverflow.com/a/33778645/855050)。但它不起作用。一般而言,我想要做的就是在用戶列表中添加一列,以顯示有關用戶的其他信息。 – becko

+0

@JoeyWilhelm我已經定義了一個'Profile'模型。 'Profile'模型有一個'ForeignKey'鏈接到'User'。因此,每個'Profile'鏈接到'User'(同一個'User'可以鏈接到幾個'Profile's)。現在我想添加一列到管理界面的'User'表格中,顯示每個用戶鏈接了多少個配置文件。 – becko

回答

-1

我想通了。只需將此添加到admin.py即可。

def profile_count(self, user): 
    return user.profile_set.count() 

UserAdmin.profile_count = profile_count 
UserAdmin.list_display += ('profile_count',) 
+0

爲什麼downvote?請留下評論。 – becko

1

您可以在list_display中包含可馴化的物品。

https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

所以只寫一個函數,給予User - 將會返回的配置文件數量,例如:

def profile_count(user): 
    return user.profiles.count() 

class UserAdmin(admin.ModelAdmin): 
    ... 
    list_display = [..., profile_count] 
    ... 

或者,你可以嘗試直接把'profiles.count'list_display,但我懷疑這會起作用。

+0

但是這不會修改整個UserAdmin表嗎? – becko

+0

我試過了,它不起作用。用戶管理表不會更改。 – becko

相關問題