[英]Index a foreign key in Django Models
I want to index a very common query in a project that involves a CharField and ForeignKey.我想在一个涉及 CharField 和 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.如果您的查询一次只访问一个字段,更好的方法是在每个字段后添加
db_index=True
。
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.但是,请记住,为查询找到最佳索引很大程度上取决于您的上下文,最好的方法是使用 SQL EXPLAIN,例如使用 django-debug-toolbar 来查找它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.