views:

39

answers:

1

Hi,

I'm using Django's User management in combination with UserProfiles that are linked to the User model with ForeignKeys. Now, I'd like to make fields from the users' profiles searchable from the UserAdmin.

My best guess was to user something like this:

class UserAdmin(auth.admin.UserAdmin):

    def field_name(self, obj):
        return obj.get_profile().name

    list_display = ('field_name',)

    search_fields = ('field_name',)

Whereas list_display works fine, search_fields gives me an error message when submitting a query: *Cannot resolve keyword 'field_name' into field. Choices are: [...]*

Do you have any clue on how to do this? Thank you in advance.

+1  A: 

You can use queryset notation with the double underscore __ to indicate joins eg.

 search_fields = ('company_name','user__username')

http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

for more

michael
The real problem is that the `auth_user` table does not have a ForeignKey to the profile model but the other way round. The only connection in the user model is the `.get_profile()` method which can't be accessed using the double underscore because it's a method—not a field.
Jannis
Sorry, reverse relationships can work. something like profile__name or profile__name__contains depending on your schema. It's good to tease these things out in ipython. It will be User.objects.filter(what__you__want='foo'). you might want to publish your profile model if you are still having probs
michael
Thank you, michael. Reverse relationships did the trick. I don't know why I didn't get that already from your link to the django docs. Maybe I was just too tired to think clearly.
Jannis