2012-05-11 156 views
0

我有這兩個模型和modeladmin。在可用主機用戶列表中添加新主機時,只會出現未分配給其他主機的主機用戶。 問題是如果我編輯一個已經創建的主機,它的實際hostuser id也被過濾了,所以我想要做的就是排除當前分配的hostuser id。 如何在hostuser字段中排除當前ID?Django - 在render_change_form(ModelAdmin)中獲取對象ID

,我需要的是*之間

在此先感謝

Models.py

class HostUser(models.Model): 
    name = models.CharField(max_length=200) 
    {..More Data..} 

class Host(models.Model): 
    {..More Data..} 
    hostuser = models.ForeignKey(HostUser, blank=True, null=True) 

Admin.py

class HostAdmin(admin.ModelAdmin): 
    {..More Data..} 
    def render_change_form(self, request, context, *args, **kwargs): 
     list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None).exclude(hostuser__id=**ACTUAL HOSTUSER_ID**) 
     list_names = [int(ids) for ids in list_names] 
     context['adminform'].form.fields['hostuser'].queryset = HostUser.objects.exclude(id__in=list_names) 
     return super(HostAdmin, self).render_change_form(request, context, args, kwargs) 
+0

會不加'唯一= TRUE'您ForeignKey的完成同樣的目標,但要確保你不會在代碼中犯錯誤? –

+0

該過濾器應用有兩個原因,第一個禁用兩個主機具有相同的hostuser,可以有效地解決獨特的設置,但第二個原因是過濾器不會顯示所有hostuser可供選擇(可以是數百個)顯示只有那些還沒有分配(這將是一些)。 –

+0

如果您已解決該問題,請將其作爲答案發布,以便對其他人有所幫助。 – arulmr

回答

0

(回答問題編輯書面聲明。轉換爲社區wiki答案。請參閱What is the appropriate action when the answer to a question is added to the question itself?

的OP寫道:

使用kwargs解決,的ModelAdmin看起來是這樣的:

def render_change_form(self, request, context, *args, **kwargs): 
    try: 
     list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None).exclude(hostuser__id=kwargs['obj'].hostuser.id) 
    except: 
     list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None) 
    list_names = [int(ids) for ids in list_names] 
    context['adminform'].form.fields['hostuser'].queryset = HostUser.objects.exclude(id__in=list_names) 
    return super(HostAdmin, self).render_change_form(request, context, args, kwargs)