Newbie question: can foreign key fields used as search fields on admin page?

737 views
Skip to first unread message

Joe Z

unread,
Aug 26, 2010, 12:49:49 AM8/26/10
to Django users
On http://www.djangobook.com/en/2.0/chapter06/

in models.py:

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

def __unicode__(self):
return self.title

In admin.py:

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'publisher')
search_fields = ('first_name', 'last_name')

Is it possible to add 'publisher' into search_fields so that in admin
page books showed can be narrow down by a specific publisher? I tried
it but got the following exception:

Django Version: 1.2.1
Exception Type: TypeError
Exception Value:
Related Field has invalid lookup: icontains
Exception Location: /usr/local/lib/python2.6/dist-packages/django/db/
models/fields/related.py in get_prep_lookup, line 139

Is this not doable? or is it a bug? any fix or workaround available?
or I have to get rid of foreign key relation ship to make it
searchable?

Thank you,
Joe

Dennis Kaarsemaker

unread,
Aug 26, 2010, 2:10:16 AM8/26/10
to django...@googlegroups.com
On wo, 2010-08-25 at 21:49 -0700, Joe Z wrote:

> Is it possible to add 'publisher' into search_fields so that in admin
> page books showed can be narrow down by a specific publisher? I tried
> it but got the following exception:

Not as such, but you can add publisher__name (assuming publisher has a
name field. You use any field :))
--
Dennis K.

They've gone to plaid!

Kenneth Gonsalves

unread,
Aug 26, 2010, 6:56:57 PM8/26/10
to django...@googlegroups.com
On Wed, 2010-08-25 at 21:49 -0700, Joe Z wrote:
> class BookAdmin(admin.ModelAdmin):
> list_display = ('title', 'author', 'publisher')
> search_fields = ('first_name', 'last_name')
>
> Is it possible to add 'publisher' into search_fields so that in admin
> page books showed can be narrow down by a specific publisher? I tried
> it but got the following exception:

search_fields = ['foreign_key__related_fieldname'] (from the docs)
--
regards
Kenneth Gonsalves

Reply all
Reply to author
Forward
0 new messages