【问题标题】:Django - sort records by custom columnDjango - 按自定义列对记录进行排序
【发布时间】:2017-01-26 11:59:43
【问题描述】:

我不知道如何让管理员能够使用自定义列对记录进行排序 - hours_to_deadline(当他们点击列标题时)。就我而言,它是 timedelta。

class JobAdmin(SuperModelAdmin):
    ...
    list_display = ['id', 'identificator', 'created', 'invoice__estimated_delivery','hours_to_deadline','customer__username', 'language_from__name', 'language_to__name',
                    'delivery__status', 'confirmed', 'approved', 'invoice__final_price']
    ...


    def hours_to_deadline(self,obj):
        try:
            return (obj.invoice.estimated_delivery - now())
        except:
            return None

我找到了这个解决方案:https://stackoverflow.com/a/15935591/3371056

但就我而言,我不能只做sum 或类似的事情。

你知道该怎么做吗?

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    您不能按不是实际数据库字段的字段排序,因为所有排序都是在数据库级别完成的。如果它有一个与数据库字段相关的值,您可以在模型定义中执行类似的操作:

    hours_to_deadline.admin_order_field = 'database_field'
    

    你可以阅读更多关于它的信息 https://docs.djangoproject.com/en/1.10/ref/contrib/admin/

    【讨论】:

      【解决方案2】:

      答案是:ordering = ('-id',)

      class JobAdmin(SuperModelAdmin):
      
          list_display = ['id', 'identificator', 'created', 'invoice__estimated_delivery','hours_to_deadline','customer__username', 'language_from__name', 'language_to__name',
                          'delivery__status', 'confirmed', 'approved', 'invoice__final_price']
          ordering = ('-id',)
      
      
          def hours_to_deadline(self,obj):
              try:
                  return (obj.invoice.estimated_delivery - now())
              except:
                  return None
      

      【讨论】:

      • 我想使用 time_to_deadline 进行订购,但仅限于管理员点击订购时。
      猜你喜欢
      • 2021-12-01
      • 2020-12-09
      • 1970-01-01
      • 2019-06-09
      • 2019-05-28
      • 2019-05-26
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      相关资源
      最近更新 更多