Ilian Iliev
Ilian Iliev

Reputation: 3236

Django Admin - sorting by custom method

I know that it can to be done with annotate if you have some aggregation, but I was not able to implement it based on custom method. Bellow is the code for my model, and i want to be able 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')

Upvotes: 3

Views: 863

Answers (1)

lprsd
lprsd

Reputation: 87077

Django admin does sorting based on db queries only, for performance sake.

So, in order to sort on a annotated field, you have to override the django.contrib.admin.ModelAdmin.get_queryset with your annotated field and include that field name in the class Meta as oder_by on the Model.

Upvotes: 1

Related Questions