ashes999
ashes999

Reputation: 1324

Django check if Object in model is parent or child

below I have a model structure with Post and Comment objects:

class Post(models.Model):
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)
dels.CASCADE, null=True, related_name="replies")
    reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name="replies")

How can I check if my comment is a reply or it's not a reply? You can reply only to the parent comment meaning there are not nested replies. However, a comment may initially never have replies.

Upvotes: 1

Views: 843

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You check if the reply field is null or not, so:

class Comment(models.Model):
    
    # …
    
    @property
    def is_reply(self):
        return self.reply_id is not None

    @property
    def has_replies(self):
        return self.replies.exists()

By making use of reply_id, we avoid loading the reply model object if it exists, which can lead to an N+1 problem.

Or we can filter with:

comments_that_are_replies = Comment.objects.filter(reply__isnull=False)
comments_that_arent_replies = Comment.objects.filter(reply=None)

we can also filter on a related object with:

comments_with_replies = Comment.objects.filter(replies__isnull=False).distinct()
comments_without_replies = Comment.objects.filter(replies=None)

Upvotes: 1

Related Questions