0

I'm recently experimenting with session variables instead of writing everything in base. I'm building an app for counter sales (cart, user, customer session variables). After the order and its items are saved in DB, I want to save the customer and clear its related session variablesin request.session['customers'] dict list.

def save_customer(request, store):
    # save only customers != Client Magasin
    customers = request.session['customers'].copy()
    print(customers)
    current_customer = list(filter(
       lambda i: i['user'] == request.user.pk and i['store'] == store, customers))[0]
    id = current_customer.pop('id')
    nom = current_customer['nom']
    if nom != 'Client Magasin':
        current_customer.pop('store')
        current_customer.pop('user')
        customer = Customer.objects.create(**current_customer)
        # return Customer for adding it to order
        return customer
    else:
        # return Client Magasin
        return Customer.objects.get(pk=1)

When I print out request.session['customers'] I can see ID, STORE and USER keys. But after the lambda, those keys are removed from the original request.session['customers']

I know that because further in my code, I wan't to filter again this list

def remove_same_customer(request):
    customers_list = request.session['customers'].copy()
    print(customers_list)
    # new_customers = list(filter(
    #     lambda i:  i['store'] != request.session['cart_warehouse'] and i['user'] != 
        request.user, customers_list))
    # request.session['customers'] = new_customers
    # request.session.modified = True

I have commented the 4 last lines because they trigger an error because ID, STORE and USER keys can't be found. This is confirmed by using print(customers_list)

what am I doing wrong ? PS : dunno if dict.copy() is useful in my case but I tried this after the error raised.

Abpostman1
  • 158
  • 1
  • 8
  • 1
    Since you access keys on the elements of ``customers``, it's a *nested* dictionary. `.copy()` creates a shallow copy, i.e. only copies the outer dictionary; the inner dictionaries still are identical. – MisterMiyagi Mar 03 '22 at 15:56
  • 1
    Does this answer your question? [Deep copy of a dict in python](https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python) – MisterMiyagi Mar 03 '22 at 15:57
  • Does this answer your question? [How to copy a dictionary and only edit the copy](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) – MisterMiyagi Mar 03 '22 at 15:58
  • Oh yes ! It was my mistake. I had read about deepcopy() a few days ago and it slipped my mind. Thank you to you 2 – Abpostman1 Mar 03 '22 at 16:07

0 Answers0