[Django]-Search by foreign key id in admin

72👍

as with the other admin options, you need to use __ for foreign keys e.g.

search_fields = ['id', 'transaction__id']
👤JamesO

10👍

search_fields documentation:

You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation

Solution:

search_fields = ['id', 'transaction__id']
👤jpic

0👍

By default, the Id field which is the primary key in Django is a BigIntergerField right? That’s numbers.

So in one of the model’s field transaction table, You should set a primary_key=True.

Then when you reference it, you can enter the name of the foreign key instance.

Eg.

Table Category with one field ‘name’ is a foreign key in post_category:

I set the field ‘name’ to be its primary key.
So to reference it in searchfields,

I will type:

category__name

Doing this allows me to search by category.

You will need to delete your database and re_migrate unless it’d throw a database error because of the previously stored primary key.

If the answer above doesn’t work for you, try this. It totally worked for me.

Leave a comment