An optimized way to retrieve parents only by the last child using django ORM

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
+5
2

SQL, ( "order by c.created_date desc" .

SQL- , , 10 , - () :

class Category(models.Model):
    ...
    def last10items(self):
        return self.item_set.order_by('-created_date')[:10]

100 , , ( : django, database OS). , 10 last10items :

{% for category in categories %}
  ...
  {% for item in category.last10items %}
      ...

, - , : - , . , , . " Python - .

+3

, , select_related, , :

items = Item.objects.order_by('-category__created_date', '-created_date').select_related()
i = 0
cat = None
for item in items:
    if item.category != cat:
        print "%s: %s" % (item.category, item)
        cat = item.category
        i += 1
    if i == 10:
        break    

for , 10 , , ORM, !

0

All Articles