Update UTCDateTimeAttribute attribute in PynamoDB based on conditon

  Kiến thức lập trình

I have a PynamoDB (v6.0.0) model defined as:

class ArticleModel(Model):
    class Meta:
        table_name = "TABLE_NAME"

    id = UnicodeAttribute(hash_key=True)
    article = MapAttribute()
    created_at = UTCDateTimeAttribute(default_for_new=datetime.now(timezone.utc))
    last_modified_at = UTCDateTimeAttribute(default_for_new=datetime.now(timezone.utc))

I’m performing batch operations (batch.save and batch.delete) on the table using ArticleModel as shown below:

with ArticleModel.batch_write() as batch:
    for identifier, article_data in article_dict["add_or_update"]:
        item = ArticleModel(id=identifier, article=article_data)
        batch.save(item)
    for identifier in article_dict["delete"]:
        item = ArticleModel(id=identifier)
        batch.delete(item)

The table already has a few items in it. When I try to update these items using batch both the created_at attribute and last_modified_at attribute are getting updated with the latest datetime.

Can you please help me with:

  1. How do I make sure that created_at is only assigned once when the new item is added?
  2. How do I keep updating the last_modified_at attribute each time there is some change in the item?

LEAVE A COMMENT