0

I'd like to convert the following query intto django query model.

We have a products table which has subcategory_id. with this query we'll able to get 3 products per each category. Please help us convert this mysql query to Django query model.

ID : title : subcategory_id

    1 : A : 4
    2: B : 6
    3: C : 7
    4: D : 4
    5: E : 4
    6 : G : 4
    7: F : 6


SELECT * FROM (
    SELECT
       `products`.*,
       @rn := CASE WHEN @subcategory_id=subcategory_id THEN @rn + 1 ELSE 1 END AS rn,
       @subcategory_id := `subcategory_id`
    FROM `products`, (SELECT @rn := 0, @subcategory_id := NULL) AS vars
    ORDER BY `subcategory_id`
) AS T1
WHERE rn <= 3
Alex Seifi
  • 80
  • 1
  • 7
  • You should think the other way around. Not how to convert SQL into the Django ORM, but how to do a task with your model in the ORM. So, show us your model and tell us what you want to get out of it! – Klaus D. Oct 04 '15 at 11:38
  • 1
    try djangos raw sql, if you are not able to figure out what this monster does :) `Model.objects.raw("raw sql query here")` – marmeladze Oct 04 '15 at 11:49
  • As @marmeladze has pointed out, now that you have gone into a lot of effort to create a query you don't need to convert into into an ORM query. Just use raw. And quite frankly this particular query is going to be very hard to convert to ORM!! – e4c5 Oct 04 '15 at 14:46

0 Answers0