Mark
Mark

Reputation: 4706

Django admin: search for foreign key objects rather than <select>?

My model looks like this:

class Asset(models.Model):
    serial_number = models.CharField(max_length=100, unique=True)
    asset_tag = models.CharField(max_length=100, unique=True)

class WorkOrder(models.Model):
    asset = models.ForeignKey(Asset)

Essentially, a work order is submitted and then an admin assigns an asset to the work order. The asset_tag field is a barcode that we can scan in. When editing the work order in the Django admin, by default the asset field is displayed as a <select> widget. What we want to be able to do is have a search field so that we can scan the asset tag and then search for the right asset in the DB to associate with the work order.

I know you can customize the Django admin foreign key to a hard coded query, but I can't figure out how to get it so it does a search based on a field on the admin page.

Upvotes: 37

Views: 29617

Answers (3)

lmiguelvargasf
lmiguelvargasf

Reputation: 69755

If you are using Django >= 2.0, you can take advantage of a feature called autocomplete_fields. You must define search_fields on the related object’s ModelAdmin because the autocomplete search uses it.

Since you have a ForeignKey relationship to Asset in WorkOrder, in the admin.py of your app add the following:

from django.contrib import admin

@admin.register(Asset)
class AssetAdmin(admin.ModelAdmin):
    search_fields = ["serial_number", "asset_tag"]


@admin.register(WorkOrder)
class WorkOrderAdmin(admin.ModelAdmin):
    autocomplete_fields = ["asset"]

Add the fields you want to use for searching to search_fields, and add define autocomplete_fields as shown in the code above.

Upvotes: 37

kigawas
kigawas

Reputation: 1258

Now you can use the autocomplete_fields from django 2.0.

It's quite neat.

Upvotes: 27

arie
arie

Reputation: 18972

Did you take a look at raw_id_fields?

It should be pretty to close to what you're after.

Upvotes: 39

Related Questions