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?
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With