0

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?

Jose Cherian
  • 7,207
  • 3
  • 36
  • 39
  • While not an answer, `datetime.utcnow().replace(tzinfo=utc)` can be written as `datetime.now(pytz.utc)`. – eumiro Dec 03 '12 at 10:06

2 Answers2

1

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
Alasdair
  • 298,606
  • 55
  • 578
  • 516
-1

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.

Krystian Cybulski
  • 10,789
  • 12
  • 67
  • 98
  • Thanks, but it is same as tdelta = datetime.utcnow().replace(tzinfo=utc) - record.published which will be called for every row, isn't it? – Jose Cherian Dec 03 '12 at 10:24
  • It will be called every time render_published() is called. @Alasdair provides an answer which only calls it once. However, if a lot of time passes between the object instantiation and the time render_published, the tdelta will be off in his implementation. Imagine running a long report which first loads PostTable and after many seconds of processing, calls render_published(). It depends on how precise you need tdelta to be and how you plan on using it. – Krystian Cybulski Dec 03 '12 at 14:18