简体   繁体   中英

what is the right way to use prefetch_related or select_related to achieve this in django

hey guys i have these models class Theme(models.Model): name = models.charfield()

class Category(models.Model):
    name = models.charfield()
class Product(models.Model):
    category = models.ForeginKey(Category)
    theme = models.ForeignKet(Theme)
    ......
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')

my last question let's say i have instead these models:

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

if i have products and i want to fetch also the category and the courses related to this category too

product = LvaProducts.objects.all().select_related('category')[0]
courses = product.category.course_set

is this is the most efficient way to do this?

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

You can chain relationships in a select_related call with double underscores

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

EDIT: You can run a prefetch on a related model by using the same technique

Product.objects.select_related(
    'category'
).prefetch_related(
    'category__course_set'
)

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