【发布时间】:2020-08-30 09:34:31
【问题描述】:
问题
鉴于以下模型,我想获取所有页面的查询集,并用与页面关联的线程中的 cmets 总数进行注释,包括与页面关联的评论线程树中的所有 cmets。
我正在使用django-mptt 来存储评论树。
我可以使用comment.get_descendant_count()在python中得到这个,但是在查询所有页面时这是非常低效的
型号
class CommentThread(models.Model):
...
class Page(models.Model):
...
thread = models.ForeignKey("CommentThread", ...)
class Comment(MPTTModel):
body = models.TextField()
author = models.ForeignKey("User", ...)
# Validation ensures a comment has
# a thread or parent comment but not both
thread = models.ForeignKey("CommentThread", related_name="comments", ...)
parent = TreeForeignKey(
'self',
on_delete=models.CASCADE,
null=True,
blank=True,
related_name='children'
)
class MPTTMeta:
level_attr = 'mptt_level'
order_insertion_by=['name']
此模型允许我向页面添加多个“根 cmets”,但也可以递归地将 cmets 嵌套在每个评论下作为回复。
# Model Use Examples
thread = CommentThread()
page = Page(thread=thread)
# add page level root comments
comment1 = Comment(thread=thread, ...)
comment2 = Comment(thread=thread, ...)
comment3 = Comment(thread=thread, ...)
# add Comment Replies to comment #1
comment_reply1 = Comment(parent=comment1, ...)
comment_reply2 = Comment(parent=comment1, ...)
comment_reply3 = Comment(parent=comment1, ...)
当前方法 - 在 python 中
有效但非常低效:
page = Page.objects.first()
total_comments = [c.get_descendant_count() for c in page.thread.comments.all()]
我尝试过的
我不确定如何使用查询集和注释来实现这一点。
我知道每个 mptt 模型也会得到一个treed_id,所以我猜我需要构建一个更复杂的子查询。
要仅获取根 cmets 的数量(不包括嵌套),我可以这样做:
pages = Page.objects.all().annotate(num_comments=models.Count("thread__comments"))
num_root_comments = pages[0].num_comments
再一次,目标是获取所有 cmets,包括嵌套:
# Non working code - this kind of pseudo queryset code of what I am trying:
all_page_comments = Comment.objects.filter(tree_id__in= (Page.thread__comments__tree_id))
Page.objects.all().annotate(num_comments=Count(Subquery(all_page_comments))
提前感谢您提供的任何帮助。
解决方案
感谢@andrey 在下面的回答,得到了一个可行的解决方案。 不确定它是否最佳,但似乎在单个查询中返回正确的值。
threads = CommentThread.objects.filter(
id=models.OuterRef("thread")
).annotate(
comment_count=models.Sum(
Floor((models.F("comments__rght") - models.F("comments__lft") - 1) / 2)
)
)
qs_pages_with_comment_count = (
Page.objects
.annotate(
comment_count=models.Subquery(
threads.values("comment_count")[:1], output_field=models.IntegerField()
)
)
# Count from subquery included count of descendents of
# each "root" comment but not the root comment itself
# so we add number of root comments per thread on top
.annotate(
comment_count=models.F("comment_count")
+ models.Count("thread__comments", distinct=True)
)
)
【问题讨论】:
标签: django django-models orm django-mptt