Halloween
Halloween

Reputation: 418

Reorganizing ManyToMany models into a different order

I have an setup similar to this.

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    books = models.ManyToManyField(Book)

    def __unicode__(self):
        return self.title

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)

    def __unicode__(self):
        return self.title

Now in my admin panel I can select an author and add Books underneath that specific author. When I print out all the books for each author it prints them in the order that they were added in the admin panel.

Is it possible to modify the order in the admin panel so that when they print, they print in the order of the admin panel?

admin.py

@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
    pass

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    pass

Upvotes: 1

Views: 33

Answers (2)

Mohammed Abdelawel
Mohammed Abdelawel

Reputation: 113

as i understand you use TabularInline for books if that's right so you just need to make simple function called get_queryset

def get_queryset(self, request):
    return super(BookInlineAdmin, self).get_queryset(request).order_by('YOURFIELD')

Upvotes: 0

bertinhogago
bertinhogago

Reputation: 349

You can add inside every model a class Meta with ordering atribute, to get items in a certain order.

class Book(models.Model):
    ...
    class Meta:
        ordering = ['author']

Maybe it helps you.

Upvotes: 1

Related Questions