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')
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
.
精彩评论