python – Django: most efficient way to query many records? – Education Career Blog

I have a table with a few thousands records (products). Each product has a 4 different categories:


I wonder if is there a method, or what is the best practice, to dynamically retrive the available categories based on the categories already selected (using Ajax).

if CAT1 = green all the products with CAT1 = green will have a series of CAT2 categories and so on. I would like to know which are the CAT2 CAT3 CAT4 categories whose products match CAT1 = green. Once I set a value or CAT2 as well I would like to do the same based on CAT1 && CAT2 values.



This is a technique commonly known as “select chaining” or “chained selects”.

You can use some fairly simple javascript for this as shown in the answer to How to limit choice field options based on another choice field in django admin

You can also use a prepackaged solution such as django-smart-selects (found via the SO answer to django chain select)


Thanks for the replies. The Chained select only works partially as I don’t have a hierarchical structure.
Here is an example of data:

CAT1 = vegetables
CAT2 = heavy
CAT3 = green

CAT1 = vegetable
CAT2 = light
CAT3 = red

CAT1 = diary
CAT2 = heavy
CAT3 = red

In my template I would like to make a system so that when the users choose CAT1 = vegetables they see CAT2 options to be heavvy and light while if they choose CAT1 = diary the only option for CAT2 is heavy and so on.

My way to go would be to get a json of the entire product table and look for the available values once a category has been selected… but the products table comprises thousands of items and Im quite sure it will slow down the entire app.
There is something similar in the admin page when you add the Filter function (list_filter) as it shows only the fields that have some entries in them.


Leave a Comment