Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: use one-to-one relationship in search_fields

I am trying to to add a search to my model admin list page using the following Model and ModelAdmin classes:

models.py

from django.contrib.auth.models import User

class UserProfile(models.Model):
        user = models.OneToOneField(User)
        country = CountryField(blank=True, null=True)

admin.py

from django.contrib import admin
from models import UserProfile

class UserProfileAdmin(admin.ModelAdmin):
        list_display = ('user','country')
        search_fields = ['user']

But I get the following error while trying to access the UserProfile in admin panel:

 at /admin/profiles/userprofile/ Related Field has invalid
 lookup: icontains

I have also tried the following:

search_fields = ['user_username']

And

search_fields = ['user_name']
    def user_name(self,obj):
        return obj.user.username

Any solutions?

like image 730
Ryu_hayabusa Avatar asked Jan 13 '23 14:01

Ryu_hayabusa


1 Answers

Try using user__username, according to the lookup API “follow” notation.

like image 187
Darwin Avatar answered Jan 16 '23 03:01

Darwin