when retrieving objects in Django I want it to be divided into a group like for example get all products and the result should be 4 groups each group have 5 objects I don't mean to group by property just random groups each group have five members for example when retrieving products = Product.objects.all() i want the result to be product = [ [ {id:1, price:3}, {id:2, price:3}, {id:5, price:3}], {id:6, price:3}, {id:10, price:3}, {id:1, price:3}], {id:19, price:3}, {id:1, price:3}, {id:1, price:3}] ], so i want to like to get the query a number for example 3 so that it gives me group with 3 members in each
Asked
Active
Viewed 48 times
-1
-
Hopefully this isn't a product recommendation algorithm :) Because it would be a pretty bad one. Does this look like a good solution? [Django: get random object](https://stackoverflow.com/a/23755881/1577947) – Jarad May 13 '21 at 05:16
-
:) no it's just ordinary groups – Omar Abdelaziz May 13 '21 at 09:58
2 Answers
0
Not sure if it is what you want but take a look at it. Maybe it will help.
products = Product.objects.all()
output = []
product_list = []
i = 1
for product in products:
product_list.append(product)
if i % 3 == 0:
output.append(product_list)
product_list = []
i += 1
if product_list.length != 0:
output.append(product_list)
output:
[
[{id:1, price:3}, {id:2, price:3}, {id:5, price:3}],
[{id:6, price:3}, {id:10, price:3}, {id:1, price:3}],
[{id:19, price:3}, {id:1, price:3}, {id:1, price:3}]
]
keep in mind, that with this method you will get lists with item objects not dictionaries {id:1, price:3}

bazzuk123
- 181
- 1
- 8
-
Thank you fr your response but is there any built method in the orm that do that while getting the data? – Omar Abdelaziz May 12 '21 at 23:32
0
I don't think there's a built-in method in the ORM that does this functionality so that's how I did it
products = [products[i:i+3] for i in range(0, len(products), 3)]

Omar Abdelaziz
- 477
- 1
- 6
- 16