I have a model like this:
class Category(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey('self', null=True)
I do the query:
categories = Category.objects.filter(name__contains=something)
And I want to prefetch 2 levels of parents above the categories. So I will be able to iterate them and do
category.parent.parent
without extra queries.
In SQL that will be equivalent to LEFT JOIN with the same table two times. How to do this in django ORM?
If you are using category.parent.parent
, you are following the foreign key forwards two times. Therefore you can use select_related
.
Category.objects.filter(name__contains=something).select_related('parent__parent')
prefetch_related
would be useful if you were following the foreign key backwards (i.e. fetching the children of categories).
You may want to look at django-mptt if you are storing a tree of categories. It may make other queries more efficient.