简体   繁体   中英

django select_related vs prefetch_related in tree like table

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 (ie 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.

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