ryche
ryche

Reputation: 2094

Is it correct to put non-data related methods into Django model?

My colleague and I are discussing whether it is correct to have model methods which are not directly related to the model data. For example, methods that generate links for the admin pages.

Should these methods be in the model or it can be a separate function which accepts app_name as an argument?

class Resource(models.Model):
    ...
    @classmethod
    def __admin_list_url(cls):
        return reverse(f'admin:{cls._meta.db_table}_changelist')

    @classmethod
    def get_admin_list_url(cls, caption='', query_string=''):
        if not caption:
            return '-'
        return mark_safe(f'<a href="{cls.__admin_list_url()}{query_string}" target="_blank">{caption}</a>')

Upvotes: 0

Views: 47

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29967

It is not inherently incorrect, but I'd say it should go in your admin.py, either as a separate function or custom admin class/mixin.

Also a heads up that you probably want to use f'admin:{cls._meta.model_name}_changelist'.

Upvotes: 1

Related Questions