Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForeignKey or ManyToMany field search in Django Admin

Sorry if this has been asked but I have looked everywhere and can't seem to find what will make it click in my brain.

If I had a structure like this, is it possible to make the ForeignKey and ManyToMany field relations searchable in the admin. So when price info was to be entered the vehicle manufacturer, type, and name could be searched instead of searching through the thousands of vehicles from the drop down box?

class Manufacturer(models.Model):
    manufacturer = models.CharField(max_length=100)

class VehicleType(models.Model):
    vehicle_type = models.CharField(max_length=100)

class VehicleInfo(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    vehicle_type = models.ForeignKey('VehicleType')
    vehicle_name = models.CharField(max_length=200)

class RandomWebsitePriceInfo(models.Model):
    vehicle_info = models.ManyToManyField('VehicleInfo')
    website_price = models.FloatField()

What I would ideally like to do is either follow the relation down through drop down boxes like where I would select the manufacturer and then in the vehicle type box would be the available vehicles from that manufacturer and then in the vehicle info box would be all the vehicles that are made by that manufacturer and of that type.

Or just make the vehicle info searchable so if I put in a vehicle model it will come up.

I have looked in to raw_input and search fields but cant seem to figure it out.

Thanks Brian

like image 755
Brian Williams Avatar asked May 28 '13 21:05

Brian Williams


2 Answers

Assuming you are on the VehicleInfo admin page, in your admin.py, try adding :

search_fields = ['vehicle_name' , 'vehicle_type__vehicle_type' , 'manufacturer__manufaturer' ]

Staring with the Vehicle model, vehicle_name searches on that field.

Now manufacturer__manufacturer will search on the manufacturer. The double underscore indicates that it is not a field on the same object, but a foreign key to look up, so the first manufacturer points to the manufacturer model. The second manufacturer tells it to look up the manufacturer field on that model.

like image 96
wobbily_col Avatar answered Nov 12 '22 04:11

wobbily_col


Django does not dynamic form elements as described as one of the preferred approaches out of the box, but there are a couple of projects that use Javascript to add it.

https://github.com/digi604/django-smart-selects is the main one I see recommended.

Making the fields searchable is possible without third party projects; @wobbily_col's answer shows how to do that.

like image 34
Peter DeGlopper Avatar answered Nov 12 '22 04:11

Peter DeGlopper