Ad

Is It Correct To Put Non-data Related Methods Into Django Model?

- 1 answer

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 target="_blank" rel="nofollow noreferrer" href="{cls.__admin_list_url()}{query_string}" target="_blank">{caption}</a>')
Ad

Answer

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'.

Ad
source: stackoverflow.com
Ad