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!
A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True , but the "reverse" side of the relation will directly return a single object. In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet .
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With