Created
May 10, 2011 14:54
-
-
Save RichardBronosky/964622 to your computer and use it in GitHub Desktop.
Django admin field order by m2m (or FK) relationship
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import admin | |
from django.contrib.auth.admin import UserAdmin | |
from django.contrib.auth.models import User | |
from userprofiles.models import UserProfile | |
class UserProfileInline(admin.StackedInline): | |
model = UserProfile | |
fk_name = 'user' | |
max_num = 1 | |
def formfield_for_manytomany(self, db_field, request, **kwargs): | |
if db_field.name == "delegates_mrm": | |
kwargs["queryset"] = User.objects.extra( | |
tables=['userprofiles_userprofile'], | |
where=['"auth_user"."id"="userprofiles_userprofile"."user_id"'], | |
select={'is_report':'"userprofiles_userprofile"."manager_id"=%s' % request.user.id} | |
).order_by('-is_report', 'username') | |
return super(UserProfileInline, self).formfield_for_manytomany(db_field, request, **kwargs) | |
class CustomUserAdmin(UserAdmin): | |
inlines = [UserProfileInline,] | |
admin.site.unregister(User) | |
admin.site.register(User, CustomUserAdmin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lines 13-17 is where the magic happens