Django Python 脚本

Django Python Script

我一直在筛选文档,但我觉得我没有得到明确的答案。是否有可能 运行 类似 python 的东西

if company_name.startswith(('A')):
enter code here

来自 Django 站点或应用程序?我该怎么做?

目前我使用的代码是

            {% for TblCompanies in object_list %}
              <tr class="customer-table">
                <td>{{ TblCompanies.company_id }}</td>
                <td>{{ TblCompanies.company_name }}</td>
                <td>{{ TblCompanies.contact_phone }}</td>
                <td>{{ TblCompanies.billing_address }}</td>
                <td>{{ TblCompanies.contact_e_mail }}</td>
              </tr>
            {% endfor %}

但是我们的客户数据库太大了,必须通过列表来寻找客户是一种负担。我想使用 http://path/to/customer_list/A

之类的网址按字母顺序对其进行排序

使用slice filter,可以得到一个子串;然后将子字符串与 'A':

进行比较
{% for TblCompanies in object_list %}
  {% if TblCompanies.company_name|slice:':1' == 'A' %}
  <tr class="customer-table">
    <td>{{ TblCompanies.company_id }}</td>
    <td>{{ TblCompanies.company_name }}</td>
    <td>{{ TblCompanies.contact_phone }}</td>
    <td>{{ TblCompanies.billing_address }}</td>
    <td>{{ TblCompanies.contact_e_mail }}</td>
  </tr>
  {% endif %}
{% endfor %}

正如@Matthias 评论的那样,最好在视图中传递已过滤的 object_list。假设 object_list 是一个查询集对象:

object_list = object_list.filter(company_name__startswith='A')

排序

在将 object_list 传递给模板之前对其进行排序:

page = requests.REQUEST.get('page', 'A')  # or Get from view parameter
                                          #    depending on url conf.
object_list = (object_list.filter(company_name__startswith=page)
                          .order_by('company_name'))

更新

注意:将 app 更改为实际的应用程序名称。

urls.py:

url(r'^/path/to/site/customers/(?P<page>[A-Z])$', 'app.views.list_customers')

app/views.py:

from django.shortcuts import render

def list_compnaies(request, page):
    object_list = (Customer.objects.filter(company_name__startswith=page)
                           .order_by('company_name'))
    return render(request, 'customers/list.html', {
        'object_list': object_list,
    })

customers/list.html

{# Link to A .. Z customer pages %}
{% for page in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
<a href="/path/to/site/customers/{{ page }}">{{ page }}</a>
{# Use {% url ... %} once you learn the url tag if possible to reduce duplicated hard-coded url #}
{% endif %}

{% for TblCompanies in object_list %}
<tr class="customer-table">
    <td>{{ TblCompanies.company_id }}</td>
    <td>{{ TblCompanies.company_name }}</td>
    <td>{{ TblCompanies.contact_phone }}</td>
    <td>{{ TblCompanies.billing_address }}</td>
    <td>{{ TblCompanies.contact_e_mail }}</td>
</tr>
{% endfor %}