django - Django检查模型中的对象是父还是子
问题描述
下面我有一个模型结构Post
和Comment
对象:
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")
如何检查我的评论是回复还是不是回复?您只能回复父评论,这意味着没有嵌套回复。但是,评论最初可能永远不会得到回复。
解决方案
您检查该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)
推荐阅读
- c# - 调用 TravelItineraryReadRQ 时不断收到 ERR.SWS.CLIENT.VALIDATION_FAILED 异常
- php - 教义,如何从子类中的字段中删除@Id?
- ios - 当手指通过时,Swift Button 就像一个传感器
- google-geocoding-api - Google 地理编码以意外的语言返回响应
- android - Retrofit Body 提供空值但在 Postman 中变得完美
- python - 在 Flask-Restful 中调用资源的 2 种方法?
- c# - 绑定列表更新时未触发 ListBox SelectedIndexChanged 事件
- .net - 使用 Xunit 进行 ASP .Net Core MVC 单元测试
- c# - C# Forms:引发鼠标事件(从子级传递给父级)
- groovy - Mocking a singleton in Groovy