1

I want to generate row numbers for the Author list based on pagination. The following code displays the row number. But there is a flaw in this code:

For Example: I have 100 records on the list and I set the pagination to 25 & now I have 4 Pages. Then I visited all the 4 pages. Then I tried to visit the first page but it counts from 101 and so on. Is there any way to change the code based on pagination value?

What I want is to reset the counter to 1 if I visit the page one and then increment it for all the rows.

enter image description here

class AuthorAdmin(admin.ModelAdmin):

    indexCnt = 0

    # If you enable fields variable then you will see only these fields in the editable form
    # fields       = ['first_name', 'last_name', 'email']

    exclude             = ['created_date'] # it will exclude this field in the editable field
    list_display        = ['index_counter', 'first_name', 'last_name', 'gender', 'website', 'email', 'phone_number']
    list_display_links  = ['first_name', 'last_name']
    list_filter         = ['gender']
    search_fields       = ['first_name', 'last_name', 'email', 'summary']
    ordering            = ['id', 'first_name', 'last_name', 'gender']

    list_per_page = 25

    def index_counter(self, obj):
        self.indexCnt += 1
        return self.indexCnt

    index_counter.short_description = '#'
vkuberan
  • 31
  • 7

2 Answers2

2

Try this:

count = Author.objects.all().count()
if self.indexCnt < count:
    self.indexCnt += 1
else:
    self.indexCnt = 1
Dennisv
  • 21
  • 2
0

In the following snippet, I have explained line by line.

def get_queryset(self, request):
        # Override the default queryset method to get the order of the records by their ID
        queryset = super().get_queryset(request)
        return queryset.order_by('id')

def serial_number(self, obj):
        # Get the queryset
        queryset = self.get_queryset(self)
        # Convert the queryset into python list and get the index of the current object passing 'obj' into the index method of python list.
        index = list(queryset).index(obj)
        # Increment 1 to get the serial number
        return index + 1
General Grievance
  • 4,555
  • 31
  • 31
  • 45