Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models, @property decorator for method

Let's say I have model like this:

class Article(models.Model):
    ...

    def get_route(self):
        ...
        return data

When I want to display value returned by get_route() in admin panel I have to create custom method like this:

def list_display_get_route(self, obj):
    return obj.get_route()
list_display = ('list_display_get_route', ...)

I've recently discovered that if I decorate get_route() with @property there's no need to use list_display_get_route() and the following will work:

models.py

@property
def get_route(self):
    ...
    return data

admin.py

list_display = ('get_route', ...)

Is this correct approach? Are there any drawbacks of this solution?

like image 563
Michał Werner Avatar asked Aug 05 '16 09:08

Michał Werner


1 Answers

Using get_route in list_display should work even if you don't make it a property.

class Article(models.Model):

    def get_route(self):
        ...
        return data

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('get_route', ...)

See the list_display docs for the list of value types supported. The fourth example, "a string representing an attribute on the model", is equivalent to your get_route method.

Using the property decorator is fine if you prefer, but in this case it would make more sense to name it route.

@property
def route(self):
    ...
    return data

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('route', ...)
like image 61
Alasdair Avatar answered Sep 30 '22 14:09

Alasdair