Alfredo Di Napoli
Alfredo Di Napoli

Reputation: 2301

Search by foreign key id in admin

I'm trying to achieve something apparently simple but I couldn't find any answer, neither on Google nor here. I have a Django model, something dead-simple:

class Shipment(models.Model):
    id = models.AutoField(primary_key=True)
    transaction = models.ForeignKey(Transaction)

I would like to be able to search in my Shipment Admin page by transaction.id. To clarity, I want this (this code obviously doesn't work):

class ShipmentAdmin(admin.ModelAdmin):
    list_display = ('id', 'transaction')
    search_fields = ['id', 'transaction.id']

This can't work cause transaction.id does not name a field. Any idea? By "search" I mean be able to insert my transaction id inside the search box of the Shipment Admin page, press "search" and automatically retrieve appropriate transactions.

Upvotes: 32

Views: 29242

Answers (3)

Genevieve Ikechukwu
Genevieve Ikechukwu

Reputation: 1

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.

Upvotes: 0

JamesO
JamesO

Reputation: 25946

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

search_fields = ['id', 'transaction__id']

Upvotes: 73

jpic
jpic

Reputation: 33420

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']

Upvotes: 10

Related Questions