AttributeError:'property'对象没有属性'admin_order_field'

fan*_*err 7 django django-admin

我希望能够在模型中定义一个属性,该属性也可以使用"list_display"Admin属性中的admin_order_field显示和排序.下面是我想要定义的属性的代码(并且可以在django管理界面中进行排序)

  @property
  def restaurant_name(self):
    return str(self.restaurant)
  restaurant_name.admin_order_field = 'restaurant__name'
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误消息:

AttributeError: 'property' object has no attribute 'admin_order_field'
Run Code Online (Sandbox Code Playgroud)

当我摆脱@property装饰器时,它工作正常,但是我必须在模型实例上调用restaurant_name()而不是restaurant_name,它在如何访问模型的不同属性(实际定义为Python属性).如何在管理员中将Python属性指定为可排序?

Jos*_*ton 7

您无法将属性分配给属性,就像错误消息告诉您的那样.您有两个选择 - 删除@property装饰器,或提供只有管理员使用的包装器.

@property
def restaurant_name(self):
    return str(self.restaurant)

def restaurant_name_admin(self):
    return self.restaurant_name

restaurant_name_admin.admin_order_field = 'restaurant__name'
Run Code Online (Sandbox Code Playgroud)