我的评论模型是:
class Comment(models.Model):
body = models.CharField(max_length=255, verbose_name="comment")
message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name="comments", verbose_name="message")
author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="author")
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name='parent', default=None)
posted = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="posted")
edited = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name="edited")
def __str__(self):
return self.body
def get_create_url(self):
return reverse('wall:add-comment', kwargs={'id': self.message.id, 'pk': self.parent.id})
def get_update_url(self):
return reverse('wall:edit-comment', kwargs={'id': self.id})
如果parent为none,我需要获取parent.id的id。
答案 0 :(得分:2)
首先,如果没有parent_id
,您无法访问parent
。 (如果你没有车,你就不能驾驶你自己的车)
如果您想在parent
为None
时返回一些数据,请尝试使用
comment = Comment.objects.get(id=instance_id)
if not comment.parent:
return comment.id
return comment.parent_id
如果parent_id
有parent
,则会返回id
,否则会返回java.lang.RuntimeException: Unable to instantiate application com.mylib.library.LibApp: java.lang.ClassNotFoundException: Didn't find class "com.mylib.library.LibApp" on path: DexPathList