読者です 読者をやめる 読者になる 読者になる

Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django e-commerce part38 ManyToMany Through using the Python Shell

python shellを使って manytomany through を確認してみる

$ python manage.py shell

>>> from products.models import Variation
>>> from carts.models import Cart, CartItem
>>> 
>>> Variation.objects.all()
[<Variation: 16GB>, <Variation: 32GB>, <Variation: cs>, <Variation: cs6>, <Variation: Default>, <Variation: Default>, <Variation: Default>, <Variation: Default>, <Variation: cc>, <Variation: de>, <Variation: de>, <Variation: minidog>, <Variation: Default>, <Variation: Default>, <Variation: CC>]
>>> variation = Variation.objects.all().first()
>>> variation
<Variation: 16GB>
>>> Cart.objects.all()
[<Cart: 1>]
>>> new_cart = Cart()
>>> new_cart
<Cart: None>
>>> new_cart.save()
>>> new_cart.id
2
>>> new_cart
<Cart: 2>
>>> variation
<Variation: 16GB>
>>> quantity = 10
>>> new_cart.items
<django.db.models.fields.related.create_many_related_manager.<locals>.ManyRelatedManager object at 0x108a45cf8>
>>> new_cart.items.all()
[]
>>> CartItem.objects.get_or_create(cart=new_cart, item=variation)
(<CartItem: 16GB>, True)
>>> new_item = CartItem.objects.get_or_create(cart=new_cart, item=variation)
>>> new_item
(<CartItem: 16GB>, False)
>>> new_item = CartItem.objects.get_or_create(cart=new_cart, item=variation)[0]
>>> new_item
<CartItem: 16GB>
>>> new_item.quantity
1
>>> new_item.quantity = 10
>>> new_item.quantity = quantity
>>> new_item.save()
>>> new_cart.items.all()
[<Variation: 16GB>]
>>> new_item.quantity
10
>>> new_cart.items.all()
[<Variation: 16GB>]
>>> new_item.delete()
>>> new_cart.items.all()
[]
>>>

全体的な流れとしては、

cartを作る、variationを選ぶ →それらをCartItemに放り込む→cartを確認する→cartitemに放り込んだvariationがきちんと反映されている。(削除したら、削除もちゃんと反映されている)

という一連の動作をshellで確認している。