We want to get the parent child so that it gives me the last 10 parents, each of which has only one last child record.
For instance:
Category
- id
- name
- created_date
Item
- id
- name
- category
- created_date
Using the model structure described above, I would like to get the last 10 categories along with the last child for each category.
With just one request to the server, I would like to access all the data.
Category1.name, Category1.id, LatestItemForCat1.name, LatestItem1ForCat1.created_date
Category2.name, Category2.id, LatestItemForCat2.name, LatestItem1ForCat2.created_date
Category3.name, Category3.id, LatestItemForCat3.name, LatestItem1ForCat3.created_date
What is the optimized way to achieve this with django ORM.
This can be achieved using the following SQL query. I would prefer to use django ORM to solve this problem. Or better sql query.
select c.name, c.id, i.name, i.created_date
from
category c
inner join
item i
on c.id = i.category_id
where i.id = (select id from item order by created_date desc limit 0,1)
limit 10