Search in ForeignKey or ManyToMany in Django Admin

Sorry if this was asked, but I searched everywhere and cannot find what would make it click in my brain.

If I had such a structure, is it possible to make the relations of the ForeignKey and ManyToMany fields searchable in admin . Therefore, when price information was to be entered, could the vehicle manufacturer, type and name be found instead of searching through thousands of vehicles from the drop-down list?

 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 ideally would like to do is either follow the ratio down on the drop-down boxes, as in the place where I would select the manufacturer, and then in the vehicle type box there would be available vehicles from that manufacturer, and then in vehicle information field, be it all vehicles manufactured by this manufacturer and of that type.

Or just make the car information searchable, so if I put the car model, it will appear.

I looked at raw_input and the search fields, but didn't seem to understand it.

Thanks Brian

+4
source share
2 answers

Django does not do this out of the box, but there are several projects that use Javascript to add it.

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

+1
source

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

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

When looking at the vehicle model vehicle_name , a search is performed in this field.

Now manufacturer__manufacturer will search for a manufacturer. A double underscore indicates that it is not a field on the same object , but a foreign key to search for, so the first producer points to the manufacturer's model. The second manufacturer says he is looking for a manufacturer field on model .

+2
source

Source: https://habr.com/ru/post/1483228/


All Articles