Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'property' object has no attribute 'admin_order_field'

I want to be able to define a property in a Model that can also be displayed AND sort using admin_order_field in the 'list_display' Admin property. Below is the code for a property that I wanted to define (and be sortable in the django admin interface)

  @property
  def restaurant_name(self):
    return str(self.restaurant)
  restaurant_name.admin_order_field = 'restaurant__name'

However, I get the following error message:

AttributeError: 'property' object has no attribute 'admin_order_field'

When I get rid of the @property decorator, it works fine, but then I have to call restaurant_name() on model instances, instead of restaurant_name, which provides inconsistent style in how I access different properties of the model (which are actually defined as Python properties). How do I specify a Python property as sortable in the admin?

like image 843
fangsterr Avatar asked Jun 24 '13 03:06

fangsterr


Video Answer


2 Answers

You can't assign attributes to a property, just like the error message is telling you. You have two options - remove the @property decorator, or provide a wrapper that only the admin uses.

@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'
like image 179
Josh Smeaton Avatar answered Sep 16 '22 11:09

Josh Smeaton


Similar with Josh answer but a bit pretty and useful for me because this way also allow you short_description specifying:

def _restaurant_name(self):
  return str(self.restaurant)
_restaurant_name.short_description = ugettext_lazy("restaurant name")
_restaurant_name.admin_order_field = 'restaurant__name'
restaurant_name = property(_restaurant_name)

Now you can use _restaurant_name as callable in admin changelist_view and restaurant_name as a property anywhere else.

like image 25
Mikhail Avatar answered Sep 20 '22 11:09

Mikhail