如何将数据从变量加载到Django Paginator中?

时间:2019-10-09 09:00:44

标签: django

我需要基于变量数据创建分页器。变量只是python列表。

views.py:

def test(request):

   db = MySQLdb.connect(host="localhost",  # your host, usually localhost
                        user="pc",  # your username
                        passwd="3346378",  # your password
                        db="mc")

   cur = db.cursor()

   cur.execute('''SELECT * FROM hello left join hell on hello.Id=hell.Id ''')

   row = cur.fetchall()

因此,行是很多列表。以及如何将其加载到分页器中? 或者一种方法是为数据创建表和模型,然后使用Django ORM或其他方法使用它?

1 个答案:

答案 0 :(得分:0)

Django内置了Paginator类,您可以查看以下内容:paginator objects和此处的一些示例:Pagination examples,以在视图中使用:Using Pagination in view

如果它引用多个对象,则写多个变量名:所以它是rows而不是row

因此,在您的情况下,该视图为:

paginator = Paginator(rows, 25) # Show 25 rows per page
page = request.GET.get('page')
rows = paginator.get_page(page)
return render(request, 'example.html', {'rows': rows})

在HTML中:

{% for r in rows %}

    {{ r }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if rows.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ rows.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ rows.number }} of {{ rows.paginator.num_pages }}.
        </span>

        {% if rows.has_next %}
            <a href="?page={{ rows.next_page_number }}">next</a>
            <a href="?page={{ rows.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>