When you build a one-to-many or many-to-many model on the Django admin screen, it's displayed in pull-down format by default. There is no problem if it is small, but it is troublesome to search when the amount increases ...
In such cases, it seems that you often install django-autocomplete-light that can implement the autocomplete function, but please refer to the official Django documentation. After reading it carefully, I found that ʻautocomplete_fields`, which can implement autocomplete, is provided as a function.
This time I'm using Django 3.0.7 and Python 3.7.2.
For easy understanding, create two apps, dog
and breed
, which register the dog name and breed, and prepare each model.
$ python manage.py startapp dog
$ python manage.py startapp breed
dog/models.py
from django.db import models
from breed.models import Breed
class Dog(models.Model):
name = models.CharField("Name", max_length=255, default="", blank=True)
breed = models.ForeignKey(Breed, on_delete=models.CASCADE)
def __str__(self):
return self.name
breed/models.py
from django.db import models
class Breed(models.Model):
name = models.CharField("BreedName", max_length=255, default="", blank=True)
def __str__(self):
return self.name
Now when I register some breeds and try to register a dog, I get a lot of pulldowns like the first image.
Edit each admin.py to implement autocomplete.
breed/admin.py
from django.contrib import admin
from .models import Breed
@admin.register(Breed)
class BreedAdmin(admin.ModelAdmin):
search_fields = ('name',)
Enter the field name you want to search in search_fiedls
. Since there is only one this time, I entered the name.
dog/admin.py
from django.contrib import admin
from .models import Dog
@admin.register(Dog)
class DogAdmin(admin.ModelAdmin):
autocomplete_fields = ('breed',)
For dogs, specify the fields you want to implement autocomplete with ʻautocomplete_fields`. Only this! Insanely easy.
When I check the management screen An input field has been prepared so that you can filter properly.
By the way, I specified ForeignKey this time, but there is no problem with ManyToManyField.
dog/models.py
from django.db import models
from breed.models import Breed
class Dog(models.Model):
name = models.CharField("Name", max_length=255, default="", blank=True)
breed = models.ManyToManyField(Breed)
def __str__(self):
return self.name
Django docs --ModelAdmin.autocomplete_fields
Recommended Posts