简体   繁体   中英

Index a foreign key in Django Models

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?

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, eg with django-debug-toolbar to find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM