views:

85

answers:

2

I am looking to sort the related objects that show up when editing an object using the admin form. So for example, I would like to take the following object:

class Person(models.Model):
    first_name = models.CharField( ... )
    last_name = models.CharField( ... )
    hero = models.ForeignKey( 'self', null=True, blank=True )

and edit the first name, last name and hero using the admin interface. I want to sort the objects as they show up in the drop down by last name, first name (ascending). How do I do that?

Context

  • I'm using Django v1.1.
  • I started by looking for help in the django admin docs, but didn't find the solution
  • As you can see in the example, the foreign key is pointing to itself, but I expect it would be the same as pointing to a different model object.
  • Bonus points for being able to filter the related objects, too (eg~ only allow selecting a hero with the same first name)
+1  A: 
class Person(models.Model):
    first_name = models.CharField( ... )
    last_name = models.CharField( ... )
    hero = models.ForeignKey( 'self', null=True, blank=True )
    class Meta:
        ordering = ['-last_name', 'first_name']

http://docs.djangoproject.com/en/dev/ref/models/options/#ordering

Note: According to the SVN docs, the admin only uses the first of the ordering options, so this is the closest you're gettig to what you want.

Aviral Dasgupta
Oh, I thought the docs were saying that Meta.ordering is the default ordering when *browsing* the objects. I didn't realize it would apply to the dropdown when editing. Thanks! I'm off to try it out. **Edit** - confirmed and accepted :)
Carver
A: 

I just found this earlier answer about django admin sorting. The solution allows for multiple orderings and filtering.

Sorry about the asking the duplicate question. It's odd that the earlier question didn't show up when searching, but is now listed under related questions on the right. Anyway, I thought I would give it more link juice in case people end up here.

Carver