So, say I have models like this:
class Foo(Model):
name = CharField(max_length=200)
def latest_comment(self):
try:
object = self.comment_set.latest()
if object:
return object.when_posted.date()
except:
return ""
class Comment(Model):
when_posted = DateTimeField()
text = TextField()
Then this is the modelAdmin:
class FooAdmin(ModelAdmin):
list_display = ['name', 'latest_comment']
ordering = ['latest_comment']
admin.site.register(Foo, FooAdmin)
It throws an error when I go to the admin site saying that ‘latest_comment’ was not found in app.Foo. Having it in list_display works fine. So, my question is: Is there a way to order models in list_display by methods of the model? And if so, how?
I haven’t tested the code, but just as an idea to try to implement this with overriding the queryset of the ModelAdmin with a annotate function to sort over a field from related field: