2016-05-19 29 views
1

我的一個Django管理員「編輯對象」頁面開始加載非常緩慢,因爲另一個對象上有一個ForeignKey,它有很多實例。有沒有一種方法可以讓Django渲染該字段,但不發送任何選項,因爲我將通過基於另一個SelectBox中的選擇的AJAX將它們拉出來?Django的管理員:不要發送一個字段的所有選項?

回答

0

無論是其他的答案爲我工作,所以我讀了Django的內部,並試圖對我自己:

class EmptySelectWidget(Select): 
    """ 
    A class that behaves like Select from django.forms.widgets, but doesn't 
    display any options other than the empty and selected ones. The remaining 
    ones can be pulled via AJAX in order to perform chaining and save 
    bandwidth and time on page generation. 

    To use it, specify the widget as described here in "Overriding the 
    default fields": 

    https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/ 

    This class is related to the following StackOverflow problem: 

    > One of my Django admin "edit object" pages started loading very slowly 
    > because of a ForeignKey on another object there that has a lot of 
    > instances. Is there a way I could tell Django to render the field, but 
    > not send any options, because I'm going to pull them via AJAX based on 
    > a choice in another SelectBox? 

    Source: http://stackoverflow.com/q/37327422/1091116 
    """ 
    def render_options(self, *args, **kwargs): 
     # copy the choices so that we don't risk affecting validation by 
     # references (I hadn't checked if this works without this trick) 
     choices_copy = self.choices 
     self.choices = [('', '---------'), ] 
     ret = super(EmptySelectWidget, self).render_options(*args, **kwargs) 
     self.choices = choices_copy 
     return ret 
0

我想你可以試試raw_id_fields 默認情況下,Django的管理員使用選擇框接口()作爲ForeignKey字段。有時你不想承擔必須選擇所有相關實例以顯示在下拉菜單中的開銷。

raw_id_fields是字段的列表,你想變成一個輸入小部件的任何一個ForeignKey或ManyToManyField

,或者您需要創建一個自定義管理形式

MY_CHOICES = (
     ('', '---------'), 
) 
class MyAdminForm(forms.ModelForm): 
    my_field = forms.ChoiceField(choices=MY_CHOICES) 
    class Meta: 
     model = MyModel 
     fields = [...] 
class MyAdmin(admin.ModelAdmin): 
    form = MyAdminForm 
+0

我已經有一個自定義的管理形式,它只是我想這個小工具不具備所有

+0

您是否嘗試過使用有限選擇的ModelChoiceField – Anoop

+0

我剛剛嘗試過您的解決方案,如示例代碼中所示,它與Muhammad Tahir的人有同樣的問題。我實際上無法選擇選項列表之外的任何內容。 – d33tah

1

您可以設置查詢集該ModelChoiceField在您的ModelForm中清空。

class MyAdminForm(forms.ModelForm): 
    def __init__(self): 
     self.fields['MY_MODEL_CHOIE_FIELD'].queryset = RelatedModel.objects.empty() 

    class Meta: 
     model = MyModel 
     fields = [...] 
+0

你的意思是objects.none(),對吧?這個不起作用 - 選擇除空白選項以外的任何東西都會給出「選擇一個有效的選擇,該選擇不是可用的選擇之一」。 – d33tah

相關問題