Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User

爱⌒轻易说出口 提交于 2019-11-27 04:31:19
Daniel Roseman

One way would be to define a custom form to use for your Team model in the admin, and override the manager field to use a queryset with the correct ordering:

from django import forms

class TeamForm(forms.ModelForm):
    manager = forms.ModelChoiceField(queryset=User.objects.order_by('username'))

    class Meta:
        model = Team

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

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.

sam

This might be dangerous for some reason, but this can be done in one line in your project's models.py file:

User._meta.ordering=["username"]

For me, the only working solution was to use Proxy Model. As stated in the documentation, you can create own proxy models for even built-in models and customize anything like in regular models:

class OrderedUser(User):
    class Meta:
        proxy = True
        ordering = ["username"]
    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)

After that, in your model just change Foreign Key to:

user = models.OneToOneField(OrderedUser, unique=True)

or even more suitable

user = models.OneToOneField(OrderedUser, unique = True, parent_link = True)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!