0

I'm using the django admin and want to sort (by last_name) the dropdown list of users in a related field (ForeignKey).

I'm am using the standard User model in django. I tried the following in the model.py which is not working:

...
from django.contrib.auth.models import User

class Meta:
    ordering = ['last_name']

User.add_to_class("Meta", Meta)
...
class Application(models.Model):

    ...
    user = models.ForeignKey(User,
        verbose_name="xyz", 
        null=True, blank=True, 
        limit_choices_to={'is_active': True}, 
        on_delete=models.PROTECT) 
    ...

Why is this not working? Is there another (easy) way to do it? I probably should have gone for a custom user model. But I didn't do that and changing it now is seams a lot of work.

I am using django 2.0.5 with python 3.6.5

Any help is appreciated.

Laxas
  • 51
  • 6
  • Well you end the `user = ...` line with a comma instead of a closed bracket. – Willem Van Onsem May 17 '18 at 14:40
  • That field goes on `user = models.ForeignKey(User, verbose_name="xyz", null=True, blank=True, limit_choices_to={'is_active': True}, on_delete=models.PROTECT)` and ends with a closing bracket. – Laxas May 17 '18 at 14:47

2 Answers2

0

Why not do it in your model class

class MyModel (models.Model):
    user = models.ForeginKey(User)
    ...

    class Meta:
        ordering ['user__last_name']
HenryM
  • 5,557
  • 7
  • 49
  • 105
  • I think that will order the objects in MyModel but what I want to order is just the dropdown list that is displayed in the admin interface when I edit the field user in one instance of MyModel. – Laxas May 17 '18 at 15:05
0

It seams that the ordering in the User model is overwritten by the ordering specified in UserAdmin. Specifying my own UserAdmin solved the problem.

class MyUserAdmin(UserAdmin):
    ...
    ordering = ["last_name", "first_name"]
    ...
admin.site.register(User, MyUserAdmin)
Laxas
  • 51
  • 6