Ordering Django models using the in-model method

So, let's say I have such models:

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 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 "last_comment" was not found in app.Foo. Having this in list_display works fine. So my question is: is there a way to arrange models in list_display using model methods? And if so, how?

+6
source share
3 answers

I have not tested the code, but just like the idea to try to implement this by overriding the set of ModelAdmin queries using the annotate function to sort by field from the corresponding field:

 class FooAdmin(admin.ModelAdmin): def queryset(self, request): qs = super(FooAdmin, self).queryset(request) return qs.distinct() \ .annotate(date_of_last_comment=Max('comment__date')) \ .order_by('-date_of_last_comment') 
+3
source

An order is SQL-level functionality, and your database knows nothing about the methods in your model.

However, you can re-sort after the fact by converting your query into a list and then using something like sorted . See: http://wiki.python.org/moin/HowTo/Sorting/

For what it's worth, I doubt the sorted list will work in admin. I could be wrong, but I'm sure Django needs it to stay in the request.

+1
source

From django doc you can define your own get_ordering method.

0
source

Source: https://habr.com/ru/post/917806/


All Articles