Home > OS >  django admin site foreign key from dropdown to search_field
django admin site foreign key from dropdown to search_field

Time:11-05

Im a bit stuck at why a foreign key drop-down field in admin site is not changing to a search field. I read the documentation that states:

These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:

search_fields = ['foreign_key__related_fieldname']

I have two models:

class Company(models.Model):
    company = models.CharField(max_length=100)

class User(AbstractUser):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)

When I want to create a user manually via admin site I get a drop-down list of possible companies as foreign keys enter image description here

I though that this solution should change the drop-down to a search field but it isnt. What am I doing wrong here? How to change this foreign key field to a search field?

admin.py from django.contrib import admin from .models import Company, User

class MyAdmin(admin.ModelAdmin):
    search_fields = ['company__company']


admin.site.register(Company)
admin.site.register(User, MyAdmin)

CodePudding user response:

You should use autocomplete_fields for this. Configure search_fields on the admin that you want to search and add the foreign key to that admin/model to autocomplete_fields

class CompanyAdmin(admin.ModelAdmin):
    search_fields = ['company']


class MyAdmin(admin.ModelAdmin):
    autocomplete_fields = ['company']


admin.site.register(Company, CompanyAdmin)
admin.site.register(User, MyAdmin)
  • Related