我的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)
但由於某種原因,用戶管理表保持不變。我究竟做錯了什麼?謝謝。
此外,窺視模型和ModelAdmin將是一個巨大的幫助。 –
@LegoStormtroopr我試着定義'UserAdmin',就像[這個答案](http://stackoverflow.com/a/33778645/855050)。但它不起作用。一般而言,我想要做的就是在用戶列表中添加一列,以顯示有關用戶的其他信息。 – becko
@JoeyWilhelm我已經定義了一個'Profile'模型。 'Profile'模型有一個'ForeignKey'鏈接到'User'。因此,每個'Profile'鏈接到'User'(同一個'User'可以鏈接到幾個'Profile's)。現在我想添加一列到管理界面的'User'表格中,顯示每個用戶鏈接了多少個配置文件。 – becko