Answer the question
In order to leave comments, you need to log in
How to optimize a Django query?
Good afternoon! There are the following models:
class Product(CreationModificationDateMixin, MetaTagsMixin, ImageThumbnailMixin):
...
brand = models.ForeignKey(
Brand,
null=True,
blank=True,
related_name='products',
verbose_name='Производитель',
on_delete=models.SET_NULL
)
material = models.ForeignKey(
Material,
verbose_name='Материал',
blank=True,
null=True,
related_name='products',
on_delete=models.SET_NULL
)
class Material(models.Model):
name = models.CharField(
'Название',
max_length=100
)
class Brand(CreationModificationDateMixin, MetaTagsMixin):
country = models.ForeignKey(
Country,
blank=True,
null=True,
verbose_name='Страна производителя',
related_name='brands',
on_delete=models.SET_NULL
)
name = models.CharField(
'Название бренда',
max_length=100,
)
class Country(models.Model):
name = models.CharField(
'Название',
max_length=200
)
countries = Country.objects.all()
materials = Material.objects.all()
country_materials = []
for country in countries:
dc = {'country': country, 'materials': []}
for material in materials:
brands = Brand.objects.filter(
products__material=material, country=country).distinct()
if brands.exists():
dc['materials'].append({'material': material, 'brands': brands})
if dc['materials']:
country_materials.append(dc)
return {
'menu': menu,
'country_materials': country_materials
}
Answer the question
In order to leave comments, you need to log in
Just remove the loops and make one request:
brands = Brand.objects.filter(
products__material__in=materials,
country__in=countries
).distinct()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question