How to add methods to Django model just for single view.

I often see people adding methods to model just to use them in single view. Often those methods don’t belong to model, but there is temptation to add this there for sake of simplicity.

I was thinking about this problem and found little hack to add methods just for single view. The beauty of this trick is that it works even for list views.

Sample code:

from django.views.generic import ListView

class MyListView(ListView):
    class model(MyModel):
        def some_additional_method(self):
            return ' '.join([str(self)] * 20)

        class Meta:
            proxy = True

With this trick you have method some_additional_method available in your template without changing model.