Django session key not found using str(instance.id)

This is my scenario I have a signal on cart apps which is raised when admin delete a product in django but searching for the product key in the session is not working below is the code that I'm using

from django.db.models.signals import post_delete
from django.dispatch import receiver
from store.models import Product
from django.contrib.sessions.models import Session

@receiver(post_delete, sender=Product)
def update_cart_on_product_delete(sender, instance, **kwargs):
    # Get all sessions
      

    for session in Session.objects.all():
        data = session.get_decoded()
       
   
        print(data)
        if str(instance.id) in data:
            print(f"Instance ID {instance.id} found in cart")         
            print(instance.id)
            del data[str(instance.id)]
            session['cart'] = data
            session.save()
        else:
            print(f"Instance ID {instance.id} not found in cart") 

And on the terminal when I get the result it appear like this {'session_key': {'47': 1}} Instance ID 47 not found in cart

as you can see clear the INSTANCE.ID is in the cart '47' but django code is not able to find it even that I'm converting the key to str. Pls someone help me on this.

Given I understand it correctly, the this is data in the cart of the key, so:

from django.contrib.sessions.models import Session
from django.db.models.signals import post_delete
from django.dispatch import receiver
from store.models import Product


@receiver(post_delete, sender=Product)
def update_cart_on_product_delete(sender, instance, **kwargs):
    key = str(instance.id)
    missing = object()
    updated_sessions = []
    for session in Session.objects.all():
        data = session.get_decoded()['cart']  # 🖘 cart lookup
        if data.pop(key, missing) is not missing:
            session['cart'] = data
            updated_sessions.append(session)
    Session.objects.bulk_update(updated_sessions, fields=('session_data',))

We here also update these Session objects in bulk with .bulk_update(…) [Django-doc].

But signals are often an antipattern [django-antipatterns]. Indeed, signals for example don't run if you do operations in bulk. Typically it is better to look for logic that does not rely on signals. Disclosure: I am the author of that page.

Вернуться на верх