Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alphabetically sort the values in a many-to-many django-admin box?

I have a simple model like this one:

class Artist(models.Model):
   surname = models.CharField(max_length=200)
   name = models.CharField(max_length=200, blank=True)
   slug = models.SlugField(unique=True)
   photo = models.ImageField(upload_to='artists', blank=True)
   bio = models.TextField(blank=True)  

class Images(models.Model):
   title = models.CharField(max_length=200)
   artist = models.ManyToManyField(Artist)
   img = models.ImageField(upload_to='images')

Well, I started to insert some Artists and then I went to the Images insert form. I found that the many-to-many artist box is unsorted:

  • Mondino Aldo
  • Aliprandi Bernardo
  • Rotella Mimmo
  • Corpora Antonio

Instead of:

  • Aliprandi Bernardo
  • Corpora Antonio
  • Mondino Aldo
  • Rotella Mimmo

How can I solve this issue? Any suggestion? Thank you in advance.

Matteo

like image 561
Matteo Avatar asked Aug 24 '09 20:08

Matteo


People also ask

How do I sort data in Django admin?

When you add a calculated field Django doesn't know how to do a order_by , so it doesn't add sorting capability on that field. If you want to add sorting on a calculated field, you have to tell Django what to pass to order_by . You can do this by setting the admin_order_field attribute on the calculated field method.

What is admin site register Django?

The Django admin is an automatically-generated user interface for Django models. The register function is used to add models to the Django admin so that data for those models can be created, deleted, updated and queried through the user interface.


1 Answers

Set ordering on the Article's inner Meta class.

class Article(models.Model):
    ....

    class Meta:
        ordering = ['surname', 'name']
like image 121
Daniel Roseman Avatar answered Oct 21 '22 05:10

Daniel Roseman