Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 808
Mark Avatar asked Aug 20 '11 19:08

Mark


People also ask

Does Django index foreign keys?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .

How does ForeignKey work in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models.


2 Answers

Did you take a look at raw_id_fields?

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

like image 96
arie Avatar answered Sep 20 '22 08:09

arie


Now you can use the autocomplete_fields from django 2.0.

It's quite neat.

like image 43
kigawas Avatar answered Sep 18 '22 08:09

kigawas