danirus / django-comments-xtd

A pluggable Django comments application with thread support, follow-up notifications, mail confirmation, like/dislike flags, moderation, a ReactJS plugin and Bootstrap 5.3.
https://django-comments-xtd.readthedocs.io
BSD 2-Clause "Simplified" License
595 stars 158 forks source link

How to get timestamp from latest comment of a specific object #363

Closed Braintelligence closed 2 years ago

Braintelligence commented 2 years ago

Hello everyone,

I've tried to figure out how to actually get comments for a specific object in a view for a long time now.

It looks like all relevant examples are only for the DTL.

How would I go about fetching comments for a specific object and then get the timestamp from that object?

I imagined it would be something like XtdComment.objects.filter(...) but I don't know how to filter for my object.

danirus commented 2 years ago

Hi @Braintelligence, you first get the comments posted to that object (it requires the content_type and the primary_key), and with those you do the query. Let's say you have an object from a Django model called Quote that have comments, to list their comments in the object_comments variable you would use the filter (as you mentioned), and to get the latest posted comment in the last_comment variable you would order them and fetch the first:

object = Quote.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(object)
object_comments = XtdComment.objects.filter(content_type=content_type, object_pk=object.pk)
last_comment = object_comments.order_by("-submit_date").first()
Braintelligence commented 2 years ago

Thank you very much; sorry I figured some of this out already thanks to your comment here https://github.com/danirus/django-comments-xtd/issues/193#issuecomment-672658623

Should have posted as soon as I found out but I was still missing a few puzzle pieces and wanted to post a complete solution; you've beat me to it 😄 👍