首页 > 解决方案 > Django检查模型中的对象是父还是子

问题描述

下面我有一个模型结构PostComment对象:

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")

如何检查我的评论是回复还是不是回复?您只能回复父评论,这意味着没有嵌套回复。但是,评论最初可能永远不会得到回复。

标签: djangodjango-modelsdjango-views

解决方案


您检查该reply字段是否为空,因此:

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()

通过使用reply_id,我们避免加载回复模型对象(如果存在),这可能导致N+1 问题

或者我们可以过滤:

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

我们还可以使用以下方法过滤相关对象:

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

推荐阅读