如何显示自定义数量的模型记录

How to display a custom number of model records

在数据库中,我有20个模型对象,当我进入模型页面时,我显示所有10条记录。我想创建一个字段来定义显示多少条记录,例如 10 个条目。然后剩下的10个条目将在2页上。

我相信您正在寻找 ModelAdmin.list_per_page 选项。在您的 admin.py 文件中,定义您的管理页面并添加上述选项以及您希望的每页实例数。

# yourapp/admin.py

from django import admin
from .models import Product


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_per_page = 10   # To show 10 model instance per page

补充答案Eyob Tariku

# admin.py

@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin)
    def get_urls(self):
        urls = super().get_urls()
        info = self.get_model_info()
        custom_urls = [
            path('change-count-displayed/', self.set_count_displayed),
        ]

        return custom_urls + urls

    def set_count_displayed(self, request):
    count = int(request.POST['count'])

    if count > 0:
        self.list_per_page = count
    else:
        # Your error handling

    return HttpResponseRedirect("../")

在模板文件夹中,我创建了“count_display_form.html”和“change_list.html”

<!-- count_display_form.html -->
<form action="change-count-displayed/" method="post" style="width: 300px; display: inline-block;">
    {% csrf_token %}
    <input class='vIntegerField' type="number" step="1" pattern="\d+" name='count'{{form.count}} style="width: 75px" />
    <input type="submit" class="btn btn-outline-primary" value="Go" style="margin-right: 5px; margin-left: 15px;">
    View on page
</form>

在change_list.html我包含表格

{% include "admin/yourapp/count_display_form.html" %}