[英]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.这些字段应该是某种文本字段,例如 CharField 或 TextField。 You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:您还可以使用查找 API “跟随”符号对 ForeignKey 或 ManyToManyField 执行相关查找:
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 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.您应该为此使用autocomplete_fields 。 Configure search_fields
on the admin that you want to search and add the foreign key to that admin/model to autocomplete_fields
在要搜索的管理员上配置search_fields
并将该管理员/模型的外键添加到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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.