Search code examples
pythondjangonamespacesdjango-orm

Django orm is creating a copy of instance instead of accessing it


I have I think kind of a tricky question in Django and it's orm.

This does not work :

cartitemproduct_in_cart_session.get().quantity+=1

cartitemproduct_in_cart_session.get().save()

If I check just after that the value of cartitemproduct_in_cart_session.get().quantity, it wasn't updated

This works :

cartitem_session=cartitemproduct_in_cart_session.get()

cartitem_session.quantity+=1

cartitem_session.save()

The value was updated

But why ?

(cartitemproduct_in_cart_session is a queryset, result of a filter, but I think it doesn't matter : cartitemproduct_in_cart_session=cart_session.cartitem_set.filter(product__slug=cartitem.product.slug) )

I am guessing that somehow, when I do cartitemproduct_in_cart_session.get().quantity, the field quantity becomes a new attributes of cartitemproduct_in_cart_session.get() and isn't linked anymore to the field in the database, but I don't understand why ...

Why do you need to first assign an instance of a model to a name, in order to update the fields of that instance ?


Solution

  • cartitemproduct_in_cart_session.get().quantity+=1

    cartitemproduct_in_cart_session.get().save()

    is equivalent to:

    x = cartitemproduct_in_cart_session.get()
    x.quantity += 1
    
    y = cartitemproduct_in_cart_session.get()
    y.save()
    # note that x and y are different objects with different memory addresses
    

    while

    cartitem_session=cartitemproduct_in_cart_session.get()

    cartitem_session.quantity+=1

    cartitem_session.save()

    is equivalent to:

    x = cartitemproduct_in_cart_session.get()
    x.quantity += 1
    x.save()