Django admin:custom 搜索

Django admin:custom search

我有两个模型:

class Site_Posts(models.Model):
    title = models.CharField(max_length=300,default='')
    ...
    def __unicode__(self):
        return self.title

class Comment(models.Model):
    post_title = models.ForeignKey(Site_Posts,null=True)
    post_id = models.IntegerField(null=True,default=None)
    ...

class Comment_Admin_Form(admin.ModelAdmin):
    model = Comment
    search_fields = ('content','post_title__title',)
    ...

我想显示所有 post_title 字段等于管理搜索框小部件文本的评论,但现在只显示一个(而存在很多项)

搜索字段应该是列表,而不是元组。

class Comment_Admin_Form(admin.ModelAdmin):
    model = Comment
    search_fields = ['content','post_title__title']

您应该在您的 ModelAdmin class 中覆盖 get_search_results 方法,如下所示:

class X_Admin_Form(admin.ModelAdmin):
    def get_search_results(self, request, queryset, search_term):   # for customize search_list
        queryset,use_distinct = super(X_Admin_Form, self).get_search_results(request,queryset,search_term)
        try:
            b = Site_Posts.objects.filter(title__icontains=search_term)
            ll = []
            for item in b:
               ll.append(item.id)
            condition = Q(post_id__in=ll) | Q(another_field=search_term)
            queryset |= self.model.objects.filter(condition)

        except:
            pass

        return queryset, use_distinct