'how to make search box on the admin change list page make a search over phone_number field in User model

I want to do search over Users using their phone number, the search_list don't do that with fields of PhoneNumberField():

class User(AbstractUser, PermissionsMixin):
    phone_number = PhoneNumberField( unique=True)
    email = models.EmailField("Email address", unique=True, null=True, blank=True)
    first_name = models.CharField(_("first name"), max_length=150, blank=True)
    last_name = models.CharField(_("last name"), max_length=150, blank=True)

I tried to use this field in the admin:

class UserAdmin(admin.ModelAdmin):
    add_form = CustomUserCreationForm
    form = UserChangeForm
    search_fields = [
        "first_name",
        "last_name",
        "email",
        "phone_number",
    ]

but it didn't work.



Solution 1:[1]

I solved this by rewrite the method get_search_results to query the field PhoneField():

class UserAdmin(admin.ModelAdmin):
    add_form = CustomUserCreationForm
    form = UserChangeForm
    inlines = [UserAddressInline, UserDeviceInline]
    search_fields = ["first_name", "last_name", "email", "orders__order_ref"]

    def get_search_results(self, request, queryset, search_term):
        queryset, may_have_duplicates = super().get_search_results(
            request, queryset, search_term
        )
        queryset |= self.model.objects.filter(phone_number=search_term)
        return queryset, may_have_duplicates

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 E.Mohammed