Home > OS >  request.data changes in every variable
request.data changes in every variable

Time:10-08

I have this code:

initial_data = dict(request.data.copy())
reserve_data = dict(request.data.copy())
print(initial_data)
for key in initial_data.keys():
    merchant_data = initial_data.get(key)
    for sub_key in merchant_data.keys():
        if sub_key in keys_to_change:
            reserve_data[key].pop(sub_key)
            reserve_data[key][values_to_change.get(sub_key)] = merchant_data.get(sub_key)
print(initial_data)

As you can see, I am not changing initial_data, but it changes anyway

#before
{'22': {'domain': 'cashier.random.io', 'salt': 'ewrwerwe', 'active': 1, 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': '', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}}}
#after
{'22': {'salt': 'ewrwerwe', 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': 
'', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}, 'host': None, 'is_active': None}} 

Is there a way to avoid this? Thanks everybody

CodePudding user response:

initial_data = dict(request.data.copy())
reserve_data = dict(request.data.copy())

does shallow copies of the request data.

If you're internally modifying the contents, you'll need to use copy.deepcopy instead:

initial_data = dict(copy.deepcopy(request.data))
reserve_data = dict(copy.deepcopy(request.data))
  • Related