djangowagtaildjango-comments

save() method for django_comments_xtd model


I am using Wagtail + Django_comments_xtd + Django.

My_Django_App/models.py

from wagtail.core.models import Page
class PostPage(Page):
  ...


from django_comments_xtd.models import XtdComment
class PostComment(XtdComment):
    page = ParentalKey('PostPage', on_delete=models.CASCADE, related_name='rn_comments')

    def save(self, *args, **kwargs):
        if self.user:
            self.user_name = self.user.username
        self.page = PostDetail.objects.get(pk=self.object_pk)
        super(PostComment, self).save(*args, **kwargs)

On Wagtail CMS, if I revise an existing post which has some comments already and publish the revised post again, I thought PostComment.save() should not be triggered any more. However, during my debug, I found it was triggered unexpectedly.

I guess that I need to fine-tune PostComment.save() to achieve above intention.

After some researches on StackOverflow,

I realize that I might need to use PostComment._state.adding and force_insert within the save() to achieve my intention.

Can anyone show me how should I fine-tune PostComment.save() ?


Solution

  • I managed to figure it out myself. I was using ParentalKey to link PostComment model to wagtail page model PostPage.

    class PostComment(XtdComment):
        # page = ParentalKey('PostPage', on_delete=models.CASCADE, related_name='rn_comments')
    

    Due to how modelcluster (where ParentalKey originates from) works, every time PostPage is revised and re-published, the PostComment.save() will be triggerred.

    After I change ParentalKey to models.ForeignKey, the PostComment.save() is not triggerred anymore after PostPage is revised and re-published.

    class PostComment(XtdComment):
        # page = models.ForeignKey('PostPage', on_delete=models.CASCADE, related_name='rn_comments')