为None对象设置id

时间:2018-02-16 11:46:05

标签: django python-3.x django-models

我的评论模型是:

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。

1 个答案:

答案 0 :(得分:2)

首先,如果没有parent_id,您无法访问parent。 (如果你没有车,你就不能驾驶你自己的车

如果您想在parentNone时返回一些数据,请尝试使用

comment = Comment.objects.get(id=instance_id)
if not comment.parent:
    return comment.id
return comment.parent_id

如果parent_idparent,则会返回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