Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User

dannyman picture dannyman · Sep 24, 2009 · Viewed 19.3k times · Source

I have an application that makes use of Django's UserProfile to extend the built-in Django User model. Looks a bit like:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    # Local Stuff
    image_url_s = models.CharField(max_length=128, blank=True)
    image_url_m = models.CharField(max_length=128, blank=True)

    # Admin
    class Admin: pass

I have added a new class to my model:

class Team(models.Model):
    name = models.CharField(max_length=128)
    manager = models.ForeignKey(User, related_name='manager')
    members = models.ManyToManyField(User, blank=True)

And it is registered into the Admin:

class TeamAdmin(admin.ModelAdmin):
    list_display = ('name', 'manager')

admin.site.register(Team, TeamAdmin)

Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.

I have a similar class with:

class Meta:
    ordering = ['name']

That works great! But I don't "own" the User class, and when I try this trick in UserAdmin:

class Meta:
    ordering = ['username']

I get:

django.core.management.base.CommandError: One or more models did not validate: events.userprofile: "ordering" refers to "username", a field that doesn't exist.

user.username doesn't work either. I could specify, like image_url_s if I wanted to . . . how can I tell the admin to sort my lists of users by username? Thanks!

Answer

Greg picture Greg · Sep 24, 2009

This

class Meta:
    ordering = ['username']

should be

    ordering = ['user__username']

if it's in your UserProfile admin class. That'll stop the exception, but I don't think it helps you.

Ordering the User model as you describe is quite tricky, but see http://code.djangoproject.com/ticket/6089#comment:8 for a solution.