Updating session expire_date through update_fields without updating the entire record

I’m working on a project where I need to update the expire_date of a session without updating the entire record. I noticed that we update the modified flag to True on using set_expiry_date.

From what I understand, the update_fields method allows you to specify which fields to update when saving a model instance. However, I’m not sure if it’s possible to update only the expire_date field without updating the other fields in the record.

Code snippet:

from django.db import models

class Session(models.Model):
    expire_date = models.DateTimeField()
    # other fields...

session = Session.objects.get(id=1)
session.expire_date = datetime.now() + timedelta(days=30)
session.save(update_fields=['expire_date'])

Question:

Is it possible to update only the expire_date field using the update_fields method using ORM?

Workaround:

After some research and experimentation, I found a workaround that works for me. Instead of using the update_fields method, I used raw SQL to update the expire_date field directly. Here’s an example of how I did it:

with connection.cursor() as cursor:
    cursor.execute("""
        UPDATE django_session
        SET expire_date = TIMESTAMPADD(SECOND, %s, NOW())
        WHERE session_key = %s
    """, [settings.SESSION_COOKIE_AGE, session_key])

This code uses the connection.cursor() method to execute a raw SQL query that updates the expire_date field directly. This approach works for me, but I’m not sure if it’s the most efficient or scalable solution.

Help:

Any help or guidance on this issue would be greatly appreciated. I’m looking forward to hearing from you and learning more about this topic.

Saloni

1 Like

It is and you can achieve it exactly the way you laid it out

session = Session.objects.get(id=1)
session.expire_date = timenow.now() + timedelta(days=30)
session.save(update_fields=['expire_date'])

or more succinctly

Session.objects.filter(id=session_id).update(
    expire_date=timenow.now() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
)
2 Likes