Django:根据对象字段查询注释

时间:2012-02-23 15:41:54

标签: django

我一直在使用内置的Django评论系统,该系统运行良好。在特定的页面上,我需要列出我刚刚提到的最新X评论:

latest_comments =   
Comment.objects.filter(is_public=True, is_removed=False)  
.order_by('submit_date').reverse()[:5]

但是我现在已经在注释的父对象中引入了一个“已发布”的布尔字段,我想在上面的查询中包含它。我已经尝试过使用content_type和object_pk字段,但我并没有真正到达任何地方。通常你会做类似的事情:

Comment.objects.filter(blogPost__published=True)

但因为它不是那样存储我不知道如何继续。

3 个答案:

答案 0 :(得分:1)

posts_ids = BlogPost.objects.filter(is_published=True).values_list('id', flat=True) #return [3,4,5,...]
ctype = ContentType.objects.get_for_model(BlogPost)
latest_comments = Comment.objects.filter(is_public=True, is_removed=False, content_type=ctype, content_object__in=posts_ids).order_by('-submit_date')[:5]

答案 1 :(得分:0)

注释使用GenericForeignKey存储与父对象的关系。由于不支持使用__<field>语法的泛型关系工作相关查找的方式。

你可以使用'in'查找来完成所需的行为,但是当有很多BlogPosts时,它需要进行大量的比较。

ids = BlogPost.objects.filter(published=True).values_list('id', flat=True) # Get list of ids, you would probably want to limit number of items returned here
content_type = ContentType.objects.get_for_model(BlogPost) # Becasue we filter only comments for BlogPost
latest_comments = Comment.objects.filter(content_type=content_type, object_pk__in=ids,  is_public=True, is_removed=False, ).order_by('submit_date').reverse()[:5]

有关所有字段的说明,请参阅Comment model doc。

答案 2 :(得分:0)

你不能在一个查询中这样做。评论使用GenericForeignKey。文档说:

  

由于GenericForeignKey的实现方式,您无法使用   字段直接使用过滤器(例如filter()和exclude())via   数据库API。

相关问题