Django Admin - 按自定义方法排序
我知道如果您有一些聚合,可以使用注释来完成,但我无法基于自定义方法来实现它。下面是我的模型的代码,我希望能够按 _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')
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')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出于性能考虑,Django admin 仅根据数据库查询进行排序。
因此,为了对带注释的字段进行排序,您必须使用带注释的字段覆盖
django.contrib.admin.ModelAdmin.get_queryset
,并将该字段名称包含在class Meta
作为Model
上的order_by
。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 theclass Meta
asoder_by
on theModel
.