简体   繁体   中英

Sorting of Users Dropdown list (ForeignKey) in Django Admin

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.

Why not do it in your model class

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

    class Meta:
        ordering ['user__last_name']

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM