D
D
Dev_nab2021-04-13 23:08:53
Django
Dev_nab, 2021-04-13 23:08:53

How to get one last object in each category?

models.py

class Post(models.Model):
    title = ...
    text = ...
    category = models.ForeignKey('CategoryPost', ...)

class CategoryPost(models.Model)
    title = ...
    slug = ...


How to get one last object in each category in one queryset ?
those. Let's say there are 5 categories, you need to get the last 5 posts for each category.

MySQL DB, distinct() does not support.

So far it turns out like this:
views.py
last_posts = []
for category in CategoryPost.objects.all():
    post = Post.objects.filter(category=category).last()
    last_posts.append(post)


When there are 5 categories, it's normal, and if there are 150, then naturally the site slows down.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tested life, 2021-04-14
@krasszen2

And if you try MyModel.objects.all().count(), the resulting number can be used to access through pk.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question