我有一个客户表单,用于将数据保存到包含名字,姓氏,电话,电子邮件,地址等的表格列表中。我在列表上有一个排序功能,当单击标题时,它会从AZ中对该字段进行排序或ZA。问题是,我有一个地址字段,它是来自不同模型的外键 - 它不按字母顺序排序,而是使用各自的主键(pk)排序。
地址模型包含地址,城市,县,邮政编码和国家/地区,并按以下方式返回到表格列表:“街道名称,城市,县,国家。”
排序功能在我的template.mako中:
<thead>
<tr>
<%
# a list of column field names and labels
column_fields = (
('first_name', 'First Name'),
('surname', 'Last Name'), ,
('phone__number', 'Phone'),
('email__email', 'Email'),
('address', 'Address'),
)
columns = ( {'field':x[0], 'label':x[1]} for x in column_fields )
%>
% for column in columns:
% if column['field'] == sort_field:
<th><a href="${self.util.reverse('customers')}?sort=- ${column['field']}">${column['label']}</th>
% else:
<th><a href="${self.util.reverse('customers')}?sort=${column['field']}">${column['label']}</th>
% endif
% endfor
</tr>
</thead>
电子邮件和电话也是外键,但每个都只有一个字段可以形成他们的模型(email_ 电子邮件和电话 _number)。
将始终选择一个县,因为它是一个下拉列表并具有默认值。因此,如果未提交地址/城市字段,我希望能够按县排序。如果填写了地址/城市字段,我想按他们排序。
知道如何获取地址进行排序
我的views.py:
def customers(request):
filtered = False
sort_field = request.GET.get('sort', 'first_name')
our_customers = Customer.objects.order_by(sort_field)
form = SearchForm(request.POST or None, request.FILES or None)
if request.method == 'POST' and \
form.is_valid() and \
form.cleaned_data['search'] and \
'clear-searchform' not in request.POST:
search = form.cleaned_data['search']
search_list = search.split()
duplicated_customers = []
for item in search_list:
the_customers = Customer.objects.filter(
Q(slug__icontains=item) |
Q(first_name__icontains=item) |
Q(surname__icontains=item) |
Q(dob__icontains=item) |
Q(phone__number__icontains=item) |
Q(email__email__icontains=item) |
Q(address__address__icontains=item) |
Q(address__city__icontains=item) |
Q(address__county__icontains=item) |
Q(address__postcode__icontains=item) |
Q(address__country__icontains=item) |
Q(medical__icontains=item) |
Q(notes__icontains=item)
# need to amend so can search by organization
)
duplicated_customers = chain(duplicated_customers, the_customers)
filtered = True
our_customers = set(duplicated_customers)
elif 'clear-searchform' in request.POST:
form = SearchForm()
dictionary = dict(
form=form,
customers=our_customers,
sort_field=sort_field,
filtered=filtered,
display_name=_('Customers'),
)
return dictionary
“Q()”用于列表中设置的搜索功能。
答案 0 :(得分:0)
要对ForeignKey模型(例如county)中的字段进行排序,请使用以“__”(双下划线)分隔的外部模型和字段名称:
customers = Customer.objects.all().order_by('address__county')
https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
有条件地设置排序字段:
if address.city != '':
sort_field = 'address__city'
else:
sort_field = 'address__county'
customers = Customer.objects.all().order_by(sort_field)