Reputation: 575
The following are my models:
class A(models.Model):
a_one = models.CharField()
a_two = model.ForeignKey(B)
class B(models.Model):
b_one = models.Charfield()
b_two = models.ForeignKey(C)
class C(models.Model):
c_one = models.CharField()
c_two = models.CharField()
I would like to create a table in django admin for model A with columns a_one
, a_two
, b_one
, c_one
, and c_two
where all of them are sortable. How can I achieve this?
Upvotes: 0
Views: 251
Reputation: 4130
Django enables column sorting on every field which defines the admin_order_field
property, related fields don't define it but you can implement it by yourself creating a method which returns the related field and setting the admin_order_field
property on it.
Something like the following should do the trick:
class AAdmin(admin.ModelAdmin):
list_display = ('a_one', 'b_one', 'c_one', 'c_two')
def b_one(self, obj):
return obj.a_two.b_one
b_one.admin_order_field = 'a_two__b_one'
def c_one(self, obj):
return obj.a_two.b_two.c_one
c_one.admin_order_field = 'a_two__b_two__c_one'
def c_two(self, obj):
return obj.a_two.b_two.c_two
c_two.admin_order_field = 'a_two__b_two__c_two'
Upvotes: 2