django template system, calling a function inside a model

前端 未结 5 903
遇见更好的自我
遇见更好的自我 2020-11-27 02:47

I want to call a function from my model at a template such as:

class ChannelStatus(models.Model):
 ..............................
 .........................         


        
5条回答
  •  醉梦人生
    2020-11-27 03:35

    If you find that there are too many properties running around everywhere or you have a template filter for every other method that you write, another solution was suggested on IRC thanks @FunkyBob. It's a little well, erm, funky but it is nice in certain cases.

      class MethodProxy(object):
            """For consolidating into 1 method the calling of methods with various single args
            (suitable dictionary keys)
    
            class MyModel(models.Model):
                ...
    
                def magic(self, value):
                    # Free the ponies
    
                def thing(self):
                    return MethodProxy(self.magic)
    
            # Usage
            >>> m = MyModel()
            ...
            >>> m.thing['value'] == m.magic('value')
    
            # template
            {{ m.thing.value }}
    
            """
    
            def __init__(self, method):
                self.method = method
            def __getitem__(self, key):
                return self.method(key)
    

提交回复
热议问题