Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - sort by userprofile field in admin

I figured out how to get UserProfile information to appear in my admin field thanks to some help from you guys. Now I want to come up with a way to properly sort those fields. I'm close.

class EmployerProfileAdmin(UserAdmin):
    inlines = [EmployerProfileInline, ]
    def company(self):
        return self.get_profile().company
    company.admin_order_field = 'employerprofile'
    list_display = ('username','first_name','last_name',company,'email','password',)

This let's me sort the company field from my UserProfile (EmployerProfile) but I have to sort it according to a field in the User. The User has 'employerprofile' but that's an entire object. How does django know how to sort on that field? Is it something I can overwrite in the EmployerProfile class?

Thanks!

like image 481
JPC Avatar asked Dec 06 '25 19:12

JPC


2 Answers

As Honza said, what are you trying to order?

In general, the order in the admin change list page will follow the model's default ordering, or can be specified by ModelAdmin.ordering as a list or tuple.

like image 54
dicato Avatar answered Dec 08 '25 09:12

dicato


Perhaps you could try using the model__field approach? As others say we don't know the whole problem, but

class Meta:
    ordering = [ "user__fieldname" ]

might work (not tested). Provided you have a "user" field which is a ForeignKey and fieldname is present in the foreign model.

So something like:

class User( object ):
    fieldname = models.CharField( max_length = 255 )

class Profile( object )
     class Meta:
         ordering = [ "user__fieldname" ]
     user = models.ForeignKey( User )
like image 41
kgr Avatar answered Dec 08 '25 07:12

kgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!