views:

23

answers:

1

I'm building an ecommerce website. I have a Product model that holds info common to all product types:

class Product(models.Model):
  name=models.CharField()
  description=models.CharField()
  categories = models.ManyToManyField(Category)

Then I have SimpleProduct and BundleProduct that have FK to Product and hold info specific to the product type. BundleProduct has a m2m field to other Products.

class SimpleProduct(Product):
  some_field=models.CharField()

class BundleProduct(Product):
  products = models.ManyToManyField(Product)

When displaying the catalog I'm making one query against the Product model and then another query per product to get the additional info. This involve a large number of queries.

I can improve it by using select_related on the simpleproduct and bundleproduct fields. I can further improve it by using the select_reverse app for m2m fields like categories.

This is a big improvement but there are more required queries because a BundleProduct have several products which can also have relations to other products (configurable product).

Is there a way to have a single query against Product that will retrieve the m2m categories, one2one SimpleProduct and BundleProduct and the BundleProduct's products?

Will this custom query look like a django queryset with all the managers and properties?

Thanks

A: 

You can possibly take a look at the extra method of querysets. May give you the opportunity to add some additional fields. But if you want raw queries, you can use the raw method of managers, these will return a type of queryset, that will not however harness the full power of normal querysets but should be enough for your concerns. On that same page the execute method is also shown, this is for truly custom sql that can't even translate into raw querysets.

KillianDS
Both extra and raw seem to add additional fields to the object.Is it possible to use raw queries for deep nested objects?In my caseproduct.bundleproduct.products.all()[0].simpleproduct.categories.all()[2] ?
pablo