Django admin autocomplete filter without foreign key

w46czmvw  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(144)

我有这个模型:

class Person(models.Model):
    first_name = models.CharField(max_length=50, null=True, blank=True)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    age = models.PositiveIntegerField(null=True, blank=True)
    gender = models.CharField(choices=Gender.choices, null=True, blank=True)
    city = models.CharField(max_length=200, null=True, blank=True)

字符串
我需要为“城市”字段自动完成过滤器
https://github.com/farhan0581/django-admin-autocomplete-filter没有做这项工作

zzoitvuj

zzoitvuj1#

你可以使用django-autocomplete-light并安装它。
为城市字段创建自定义小部件:

from autocomplete_light.widgets import AutoCompleteWidget
class CityAutocompleteWidget(AutoCompleteWidget):
    def get_model_objects(self, query):
        return City.objects.filter(name__icontains=query)

字符串
更新Person模型以使用新的小部件:

class Person(models.Model):
    first_name = models.CharField(max_length=50, null=True, blank=True)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    age = models.PositiveIntegerField(null=True, blank=True)
    gender = models.CharField(choices=Gender.choices, null=True, blank=True)
    city = models.CharField(max_length=200, null=True, blank=True, widget=CityAutocompleteWidget)

相关问题