Home > Mobile >  Index a foreign key in Django Models
Index a foreign key in Django Models

Time:05-20

I want to index a very common query in a project that involves a CharField and ForeignKey. I have a bottleneck with this query and I am trying to optimize it. I have this:

class Bill(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    category = models.CharField(max_length=200, null=True, blank=True)
    ...

I added this to try to improve the performance:

class Meta:
    indexes = [
        models.Index(fields=['category', 'company']),
    ]

But the result is the same, the query is:

models.Bill.objects.filter(company=company, category='recibida')

Is there something else that I could improve? Is this indexing well done?

CodePudding user response:

The index you created is valid, but maybe not would you need. It creates a combined index of both fields and will only be used if you have a query which also used both fields.

If your query only accessing one of the fields at a time, the better approach is to add db_index=True after each field.

However, keep in mind that finding the best index for a query depends a lot on your context and the best approach is to use SQL EXPLAIN, e.g. with django-debug-toolbar to find it.

  • Related