简体   繁体   中英

django admin site foreign key from dropdown to search_field

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在此处输入图片说明

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM