![](/img/trans.png)
[英]Model to create threaded comments on Google Appengine with Python
[英]Creating threaded comments model Django
我有一個存儲comments
的模型。
class Comment(TimeStampedModel):
content = models.TextField(max_length=255)
likes = models.IntegerField(default=0)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
但是,我現在想要添加回復評論(線程評論)的能力,即
1 Comment 1
2 Reply to Comment 1
3 Reply Comment 2
4 Reply Comment 2
5 Reply Comment 4
6 Reply to Comment 1
7 Reply to Comment 1
我希望通過在評論模型中添加自我裁判相關字段來實現這一點,即
child = models.ForeignKey(Comment)
但我不確定這會起作用,以及如何使用上述方法獲得每個評論的嵌套回復。
我的問題是,有沒有正確的方法來做到這一點,以及如何?
是的,你當然可以做到這一點。 你可以找到遞歸元素,為此你應該使用django-mptt模型。 要獲取特定注釋的嵌套注釋,可以使用以下函數。
class Comment(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='sub_comment')
# Other fields
def get_all_children(self, include_self=False):
"""
Gets all of the comment thread.
"""
children_list = self._recurse_for_children(self)
if include_self:
ix = 0
else:
ix = 1
flat_list = self._flatten(children_list[ix:])
return flat_list
def _recurse_for_children(self, node):
children = []
children.append(node)
for child in node.sub_comment.enabled():
if child != self
children_list = self._recurse_for_children(child)
children.append(children_list)
return children
def _flatten(self, L):
if type(L) != type([]): return [L]
if L == []: return L
return self._flatten(L[0]) + self._flatten(L[1:])
在上面的代碼中, sub_comment
用於父字段。 你可以使用這樣的,並可以實現評論線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.