Search by foreign key id in admin

19,173

Solution 1

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

search_fields = ['id', 'transaction__id']

Solution 2

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']
Share:
19,173
Alfredo Di Napoli
Author by

Alfredo Di Napoli

Just a man struggling with programming languages. Functional, Prototype based, Object Oriented.. so long the path to the enlightenment..

Updated on June 20, 2022

Comments

  • Alfredo Di Napoli
    Alfredo Di Napoli almost 2 years

    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.