0

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.

E.Mohammed
  • 163
  • 1
  • 4
  • 13
  • I don't understand why have you added ```add_form``` and ```form``` as django provides its own forms. Comment both of them and then try. – shah sawood Mar 31 '22 at 13:05
  • @shahsawood, we are using a `AbstractUser` so we customized the create form for the model in the admin site – E.Mohammed Mar 31 '22 at 22:46

1 Answers1

0

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
E.Mohammed
  • 163
  • 1
  • 4
  • 13