0

I am trying to update a set of instances based on the current values per instance.

responses.update(
    last_paused=now(),
    duration=F('seconds_remaining')-(now() - F('last_accessed')).total_seconds()
)

But I get this error:

Traceback (most recent call last):
  File "/vagrant/Devel/env/lib/python3.5/site-packages/celery/app/trace.py", line 382, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/vagrant/Devel/env/lib/python3.5/site-packages/celery/app/trace.py", line 641, in __protected_call__
    return self.run(*args, **kwargs)
  File "/vagrant/Devel/apps/assessments/tasks.py", line 101, in section_pause
    duration=F('seconds_remaining')-(now() - F('last_accessed')).total_seconds()
AttributeError: 'CombinedExpression' object has no attribute 'total_seconds'

I am trying to workaround updating each row by itself.

The model I am trying to save into looks like this:

class Response(models.Model):
    exam_response = models.ForeignKey(ExamResponse)
    section = models.ForeignKey(Section)
    started = models.DateTimeField(default=now)
    ended = models.DateTimeField(null=True)
    seconds_remaining = models.PositiveIntegerField(default=0)
    last_accessed = models.DateTimeField(default=now)
    last_paused = models.DateTimeField(default=None, null=True)

With Postgres, you could do something like this to get the value needed, but not sure how to apply it in Django ORM.

select extract('epoch' from timestamp);
nael
  • 1,441
  • 19
  • 36

1 Answers1

0

I ended up changing the seconds_remaining field to a Duration Field.

With that change, I am able to use the following code to do a bulk update:

responses.update(
    last_paused=now(),
    duration=F('seconds_remaining')-(now() - F('last_accessed'))
)

The expressions F('seconds_remaining')-(now() - F('last_accessed')) evaluates into a timedelta object.

nael
  • 1,441
  • 19
  • 36