pythondjangoperformancedjango-modelsindices

Are multiple Django indices necessary?


I've a Django model that, among other fields, has time, station and variable. Nearly always, queries will be done providing the three fields - occasionally and very rarely, I might want to query using only one of them.

In this case, does it matter if the index is set to models.Index(fields=["station", "time", "variable"]) or models.Index(fields=["time", "station", "variable"]) or other permutation of the three? Would it be useful to add all possible permutation or is it irrelevant? If there any performance penalty or benefit in adding all permutations?

Many thanks!


Solution

  • Django generates the query based on the alphabetical order of the field names, and your index shall match that so the database can use the index. so your index shall be "station", "time", and "variable". If that will despairs the index, you can use Django raw query which can return model objects if your query includes the primary key