0

I have a Folder model and I want to display the columns in the admin page ordered alphabetically following the __str__ method.

I looked over several similar questions like this one, this one and also this one, but didn't manage to really understand the answers, or at least enough to adapt them to my problem (even though I've been trying for quite some time).

Here is my Folder class, with the str method I want to sort with :

class Folder(models.Model):
    folder_name = models.CharField(max_length=200)
    parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        if self.parent_folder:
            return f'{self.parent_folder}/{self.folder_name}'
        else:
            return self.folder_name

And my FolderAdmin class :

class FolderAdmin(admin.ModelAdmin):
    ordering = ('str',) #I want it to do like that but don't know how to do it
    
    fieldsets = [
        (None,            {'fields': ['folder_name']}),
        ('Parent Folder', {'fields': ['parent_folder']}),
    ]
    
    list_display = ('folder_name', '__str__')

I feel dumb for not understanding a question already answered multiple times but if you could help me understand it I'd be grateful.

Thank you in advance !

Balizok
  • 904
  • 2
  • 5
  • 19
  • 2
    Why not simply do `ordering = ('parent_folder', 'folder_name')`? That does exactly what you want right? First order on parent folder (if any), then on folder_name. – The Pjot May 12 '22 at 09:57
  • That seems to work, thank you so much ! That was so simple, it's frustrating... – Balizok May 12 '22 at 10:10

0 Answers0