remove the default select in ForeignKey Field of django admin
<p>There are 150k entries in User model. When i am using it in django-admin without the raw_id_fields it is causing problem while loading all the entries as a select menu of foreign key. is there alternate way so that it could be loaded easily or could become searchable?</p>

<p>I have these models as of defined above and there is a User model which is used as ForeignKey in ProfileRecommendation models. The database entry for user model consist of around 150k entries. I don't want default select option for these foreign fields. Instead if can filter them out and load only few entries of the user table. How I can make them searchable like autocomplete suggestion?</p>

<p>admin.py</p>

<pre><code>class ProfileRecommendationAdmin(admin.ModelAdmin):
list_display = ('user', 'recommended_by', 'recommended_text')
raw_id_fields = ("user", 'recommended_by')
search_fields = ['user__username', 'recommended_by__username',]
admin.site.register(ProfileRecommendation, ProfileRecommendationAdmin)
</code></pre>

<p>models.py</p>

<pre><code>class ProfileRecommendation(models.Model):
user = models.ForeignKey(User, related_name='recommendations')
recommended_by = models.ForeignKey(User, related_name='recommended')
recommended_on = models.DateTimeField(auto_now_add=True, null=True)
recommended_text = models.TextField(default='')
</code></pre>

<p>you can use method formfield_for_foreignkey</p>

<p>something like this:</p>

<pre><code>class ProfileRecommendationAdmin(admin.ModelAdmin):


   def formfield_for_foreignkey(self, db_field, request, **kwargs):
     if db_field.name == "user":
       kwargs["queryset"] = User.objects.filter(is_superuser=True)
     return super(ProfileRecommendationAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)
</code></pre>

<p>or other way is to override the form for that modeladmin class</p>

<pre><code>from django import forms
from django.contrib import admin
from myapp.models import Person

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        exclude = ['name']

class PersonAdmin(admin.ModelAdmin):
    exclude = ['age']
    form = PersonForm
</code></pre>

<p>you can change the widget and use something like the selectize with autocomplete and ajax.</p>

python django django-forms django-admin