A
A
Andrey Salnikov2017-10-17 13:32:01
Django
Andrey Salnikov, 2017-10-17 13:32:01

How to optimize image queries in Django model?

There are such models:

class Product(models.Model):
    name = models.CharField()
    color_variant_of = models.ForeignKey('self', blank=True, null=True, related_name="color_variants", verbose_name='Вариант цвета')

class ProductColor(models.Model):
    name = models.CharField()
    hex_name = models.CharField()

class ProductInfo(models.Models):
    product = models.OneToOneField(Product)
    color = models.ForeignKey(ProductColor)

class ProductImage(models.Model):
    product = models.ForeignKey(ProductColor)
    image = models.ImageField()

I'm making a catalog page. You need to display mini-cards in which the image will change depending on the selected color. A product can have multiple colors and this is done via color_variant_of.
That is, I take the product (Product), then I take all the color options - product.color_variants__set.all, from which I take the color - product.productinfo.color (as well as all other color options) and images product.productimage__set.all
All this results in 500 or more queries to the database when generating a template.
What to do with it? Do I need to somehow change the architecture of the project or cache something, or can I somehow connect requests together before rendering the template?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2017-10-17
@Shshzik

prefetch_related
And yes, prefetch_related can be customized so that it does not fetch everything

A
Astrohas, 2017-10-17
@Astrohas

First of all, it's a strange structure.
Firstly, why make a separate Product info model if they still have a 1k1 connection? Move fields from ProductInfo to Product.
Use Select_related first , then you can use prefetch related.
If it doesn’t help (well, you never know), you can do monkey patching

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question