Home > Software design >  what is the right way to use prefetch_related or select_related to achieve this in django
what is the right way to use prefetch_related or select_related to achieve this in django

Time:08-02

hey guys i have these models

class Category(models.Model):
    name = models.charfield()
class Product(models.Model):
    category = models.ForeginKey(Category)
    ......
class Order(models.Model):
    product = models.ForeigKey(Product)

i want to fetch the product and the category of the product from an order instance in one query, i know that for forward foreignkey you should use select related but i don't think there's a way to fetch the product category when you use this:

Order.objects.all().select_related('product')

so is it right to use this one then:

Order.objects.all().prefetch_related('product__category')

CodePudding user response:

Since the relation from Order to Product is a many-to-one relation, and that of Product to Category is a many-to-one relation, you fetch these both through .select_related(…) [Django-doc]:

Order.objects.select_related('product__category')

CodePudding user response:

You can chain relationships in a select_related call with double underscores

Order.objects.all().select_related('product__category')
  • Related