Django Admin - custom method sorting

I know that this can be done with annotation if you have aggregation, but I could not implement it based on a custom method. Bellow is the code of my model, and I want to sort the results by _is_registered.

class Subscribers(models.Model):
    email = models.EmailField(_('E-mail'))
    want_newsletter = models.BooleanField(default = False)

    def get_user(self):
        user = User.objects.filter(email= self.email)
        if user.count()>0:
            return user[0]
        return None

    def _is_registered(self):
        user = self.get_user()
        if user:
            return _('Yes')
        return _('No')
+3
source share
1 answer

The Django admin only performs sorting based on db requests, for the sake of performance.

So, to sort by annotated field, you need to override django.contrib.admin.ModelAdmin.get_querysetusing the annotated field and include this field name in class Metaas oder_byin Model.

+1
source

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


All Articles