Home > Back-end >  add ordinal number to django admin list_view
add ordinal number to django admin list_view

Time:01-13

I want to add an ordinal number for each row in in list view in the admin panel for my models.

I tried adding something like this in my MYModelAdmin(ModelAdmin)

line_numbering = 0

  def line_number(self, obj):
      self.line_numbering  = 1
      return self.line_numbering

but i add more and more numbers, is there an easy way to add an ordinal number without adding a field to your model ?

CodePudding user response:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('ordinal_number', 'field1', 'field2')

    def ordinal_number(self, obj):
        # get the queryset of MyModel objects
        queryset = self.model.objects.all()
        # return the index of the current object   1
        return list(queryset).index(obj)   1
    ordinal_number.short_description = 'Number'

admin.site.register(MyModel, MyModelAdmin)
  • Related