1👍
✅
You can get the last comment with:
post.comments.latest('date_posted')
or if you want the latest per date_updated
, you use:
post.comments.latest('date_updated')
If you want to obtain the last comment per post, you can work with a Prefetch
object:
from django.db.models import OuterRef, Subquery
posts = Posty.objects.annotate(
latest_comment=Subquery(
CommentPost.objects.filter(
post=OuterRef('pk')
).values('content1').order_by('-date_posted')[:1]
)
)
then in the template, you can render with:
{% for post in posts %}
{{ post.last_comment }}
{% endfor %}
Source:stackexchange.com