Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 662
Alfredo Di Napoli Avatar asked Feb 07 '12 09:02

Alfredo Di Napoli


2 Answers

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

search_fields = ['id', 'transaction__id']
like image 175
JamesO Avatar answered Nov 09 '22 17:11

JamesO


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']
like image 26
jpic Avatar answered Nov 09 '22 15:11

jpic