Search code examples
pythondjangopython-2.7django-1.4django-tables2

using datetime.utcnow() with DjangoTables2 render_FOO


I am trying to display the age of a post(in hours) with djangotables2. My code is given below

class PostTable(tables.Table):
    current_Time = datetime.utcnow().replace(tzinfo=utc)
    published= tables.Column()
    def render_published(self, value,record):
        tdelta = self.current_Time - record.published
        #Some logic 

With this code, 'current_Time' is only updated when the apache server restart. If I change my code to

  tdelta = datetime.utcnow().replace(tzinfo=utc) - record.published

it works, but calculates datetime.utcnow() for every row which is not efficient. I want 'current_Time' to be updated only once for table. What is the best way to achieve that?


Solution

  • Try setting the current time in the table's __init__ method. Then self.current_Time will be set each time the table is initiated, rather than when the table is defined.

    class PostTable(tables.Table):
        def __init__(self, *args, **kwargs):
            super(PostTable, self).__init__(*args, **kwargs)
            self.current_Time =  datetime.utcnow().replace(tzinfo=utc)
    
        def render_published(self, value,record):
            tdelta = self.current_Time - record.published