issue with setting dynamo db created_at field

193 Views Asked by At

I am trying to add a new field 'created_time' in my existing dynamodb. another field 'updated_time' field already exists.

I want to set the created_time only once, when the new record is created. updated_time updates at every change in record using .save() function of pynamodb.

For this purpose I am using default_for_new for created_time in my django model class. But still my created_time is updated even when updated_time updates. (they are kind of moving in sync)

Below is my code:

from pynamodb.models import Model
from pynamodb.attributes import  UTCDateTimeAttribute
from datetime import datetime


class MyModel(Model):
    id = UnicodeAttribute(hash_key=True)
    created_time = UTCDateTimeAttribute(default_for_new=datetime.utcnow)
    updated_time = UTCDateTimeAttribute(default=datetime.utcnow())

and I am using the code as

def fun(key, isrecordexist):
    data = MyModel(id=key, updated_time=datetime.utcnow(), created_time=datetime.utcnow)
    if isrecordexist:
          data.save(MyModel.id.does_not_exist())
    else:
          data.save()

isrecordexist is a bool value that is passed if record already exist in table.

I have already tried the solution in Saving object creation datetime using Pynamodb

1

There are 1 best solutions below

2
Leeroy Hannigan On

If pynamodb works like the official DynamoDB SDK then created_at will create a new timestamp everytime you create a new local object of a class. This is not done on the server side, but the client side.

To overcome your issue you would first need to read the item and set the created_time as it will be auto crated if the value is null.