Question

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?

Was it helpful?

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

OTHER TIPS

current_Time is a field on your class which is installed when your class deffinition is read in. This happens once when your class is initially defined. In your case, this happens at server startup. The value for current_Time is set then and only once.

You will want to move current_Time = datetime.utcnow().replace(tzinfo=utc) into the def render_published(self, value,record):

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

This way, current_Time will be populated every time the render_published method is called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top