Skip to content

Instantly share code, notes, and snippets.

@RichardBronosky
Created May 10, 2011 14:54
Show Gist options
  • Save RichardBronosky/964622 to your computer and use it in GitHub Desktop.
Save RichardBronosky/964622 to your computer and use it in GitHub Desktop.
Django admin field order by m2m (or FK) relationship
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)
@RichardBronosky
Copy link
Author

lines 13-17 is where the magic happens

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment