我在使用django
和django-tables2列出数据方面存在问题,我无法理解。
情境:
我有一个显示记录列表的视图。在该视图中还是用于搜索特定记录(家庭)的搜索框。显示的每条记录都有一个字段(家庭大小),该字段是其中的其他记录(人员)的总计数。即HouseHold 1中有5人。
问题在于,最初加载页面时,会显示正确的家庭记录大小。例如,使用上面给出的示例,它将显示HouseHold 1的家庭大小5.参见下图并记下第一条记录的家庭大小。
但是当我输入特定家庭记录的搜索词时,返回的结果总是显示家庭大小的平方,即在我的情况下为25(5 * 5)。见下图:
有人可以帮我弄清楚这个价值的来源吗?
以下是我的代码:
urls.py
from apps.org.urls import office_url
from lib.security import secure_url as sec
... # Non-relevant code removed
sec(office_url('/household/list/$'),
registration_views.HouseholdList.as_view(),
name='household.list'),
views.household.py
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import transaction
from django.db.models import Count
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext_lazy as _
from django_tables2 import tables
from apps.registration.models import Household, Person
from lib.views import CoreListView
... # Non-relevant code left out for brevity and clarity
class HouseholdTable(tables.Table):
name = DetailUrlColumn()
location = tables.Column()
household_size = tables.Column(verbose_name=_("Household size"))
registration_date = tables.Column()
registration_user = tables.Column(verbose_name='Registered by')
document_id = DocumentListColumn(_('Document ID'), accessor='recipient_candidate', orderable=False)
action = ActionColumn(orderable=False,
actions=(
("delete", Household.get_delete_url, "btn-warning", "icon-remove-sign"),
("edit", Household.get_detail_url, "btn-info", "icon-edit"),
)
)
class Meta:
order_by = ("name")
empty_text = _("no household to display")
class HouseholdList(SelectedOfficeMixin, CoreListView):
template_name = 'registration/beneficiary/list.html'
model = Household
table_class = HouseholdTable
permissions = ['registration.view_household']
search_fields = ('name', 'members.documents.document_num')
def get_queryset(self):
"""Annotate so that the queryset can be ordered by household size."""
return self.selected_office.households.with_related_members().annotate(household_size=Count('members'))
def get_doc_url(self):
doc_root_url = super(HouseholdList, self).get_doc_url()
return urlparse.urljoin(doc_root_url, 'how_to_register_a_new_beneficiary_household.html')
lib.views.py
... # Non-relevant code left out
class CoreSearchMixin(object):
"""Subclasses must define search_fields = [field_1, ...field_n]
where the field is a string, the name of a field, and can contain the following prefix characters:
'^': the search field must start with the search term, case insensitive
'=': the search field must exactly equal the search term, case insensitive
'@': full-text search
If no prefix is given, any string that contains the search field will match.
"""
search_fields = None
search_form_class = SearchForm
@cachedproperty
def search_form(self):
return self.search_form_class(getattr(self.request, self.request.method))
def get_query_help_message(self):
"""Returns a comma separated list of fields that are used in the search, to help the user
create a search.
"""
fields = []
if self.search_fields:
for search_field in self.search_fields:
field = get_field_from_path(self.model, search_field)
fields.append(field.verbose_name.title())
return ",".join(fields)
def get_filtered_queryset(self, queryset):
if self.search_form.is_valid():
self.query = self.search_form.cleaned_data['q']
else:
self.query = None
if self.search_fields and self.query:
orm_lookups = (construct_search(str(search_field).replace('.', '__'))
for search_field in self.search_fields)
chained_or_queries = None
for bit in self.query.split():
or_queries = (models.Q(**{orm_lookup: bit})
for orm_lookup in orm_lookups)
if chained_or_queries:
chained_or_queries = itertools.chain(chained_or_queries, or_queries)
else:
chained_or_queries = or_queries
return queryset.filter(reduce(operator.or_, chained_or_queries))
else:
return queryset
def get_context_data(self, **kwargs):
return super(CoreSearchMixin, self).get_context_data(
search_form=self.search_form,
query_help_message=self.get_query_help_message(),
search_fields=self.search_fields,
**kwargs
)
class CoreListView(CoreSearchMixin, ListView):
"""Displays a simple searchable list.
Subclasses must define search fields as per CoreSearchMixin
"""
template_name = 'cv/generic/list.html'
table_class = None
paginate_by = 10
def get_table_class(self):
return self.table_class
def get_table(self, filtered_queryset):
return self.get_table_class()(filtered_queryset)
def get_context_data(self, **kwargs):
table = self.get_table(self.get_filtered_queryset(self.get_queryset()))
table.paginate(page=self.request.GET.get('page', 1), per_page=self.paginate_by)
RequestConfig(self.request, paginate=False).configure(table)
return super(CoreListView, self).get_context_data(table=table, **kwargs)
我在这里失踪了什么?