2015-09-14 16 views
17

我有以下型號:間接直列

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 

class Property(models.Model): 
    user = models.ForeignKey(User) 

我想創建一個TabularInline顯示連接到特定UserProfile其Django管理頁面中的所有屬性。這裏的問題是,當然,物業沒有一個ForeignKey直接UserProfile,所以我不能簡單地寫

class PropertyTabularInline(admin.TabularInline): 
    model = Property 

class UserProfileAdmin(admin.ModelAdmin): 
    inlines = (PropertyTabularInline,) 

如何我容易嗎我想要什麼?

回答

1

您可以覆蓋用戶管理頁面以同時顯示ProfileProperty型號。

from django.contrib import admin 
from django.contrib.auth.admin import UserAdmin 
from myapp.models import * 

class ProfileInline(admin.TabularInline): 
    model = Profile 

class PropertyInline(admin.TabularInline): 
    model = Property 

class UserAdmin(UserAdmin): 
    inlines = (ProfileInline, PropertyInline,) 

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

也可以被顯示(例如組或權限)刪除任何不必要的/未使用的用戶屬性

更多在這裏:https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-the-existing-user-model

這裏: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example

+1

這不是我想要的,但是 - 我想要在配置文件管理頁面上顯示內聯,而不是用戶管理頁面。 – haroba

0

這是可以實現的通過對模型進行一次更改。

UserProfileUser,子類User創建UserProfile而不是創建一對一關係。代碼應該看起來像:

class UserProfile(User): 
    # some other fields, no relation to User model 

class Property(models.Model): 
    user = models.ForeignKey(User) 

,這將導致創建UserProfile模型已隱藏OneToOne關係User模型,也不會重複的用戶模型。

做了這樣的改變之後,你的代碼就可以工作了。有一些變化引擎蓋下,如UserProfile不再有它自己的ID,您可以訪問UserUserProfile內的字段,它很難交換User模型使用settings.AUTH_USER_MODEL(這將需要創建一些自定義函數返回適當的類型和手動更改遷移)但如果​​這對你來說不是問題,那可能是一個很好的解決方案。

+0

這不是一個替代方案。這裏的要點是,我*不*希望用戶的字段可以在UserProfile上訪問,因爲我有幾個UserProfile-like模型與具有不同訪問控制的用戶的OneToOne關係等。 – haroba

1
class PropertyTabularInline(admin.TabularInline): 
    model = Property 

    def formfield_for_dbfield(self, field, **kwargs): 
     if field.name == 'user': 
      # implement your method to get userprofile object from request here. 
      user_profile = self.get_object(kwargs['request'], UserProfile) 
      kwargs["queryset"] = Property.objects.filter(user=user_profile) 
     return super(PropertyInLine, self).formfield_for_dbfield(field, **kwargs) 

一旦做到這一點,你可以添加這個在線用戶UserProfileAdmin喜歡:

class UserProfileAdmin(admin.ModelAdmin): 
    inlines = (PropertyTabularInline,) 

沒有測試,但應該工作。

+0

這不適用於django 1.8和可能也是1.7,它會在系統檢查時失敗:':(admin.E202)'app.Property'沒有'app.UserProfile'的ForeignKey。' – GwynBleidD

+0

@GwynBleidD:working in django1.8在我的應用程序 –

+0

所有執行系統檢查的操作都將失敗,例如創建新的遷移。 – GwynBleidD