◐ Shell
clean mode source ↗

Python PR with issues: Inventory Management and Cart Features by trulyfurqan · Pull Request #1 · gitbito/Examples

from fastapi import APIRouter, Depends, HTTPException
from models import User, Cart, CartItem, Product
from authentication import get_current_user
router = APIRouter()
@router.post("/cart/add")
async def add_to_cart(
product_id: int, quantity: int, user: User = Depends(get_current_user)
):
product = await Product.get(id=product_id)
cart, _ = await Cart.get_or_create(user=user)
cart_item, created = await CartItem.get_or_create(cart=cart, product=product)
if not created:
cart_item.quantity += quantity
else:
cart_item.quantity = quantity
cart_item.price = product.new_price
await cart_item.save()
return {"message": "Item added to cart"}
from fastapi import APIRouter, Depends, HTTPException
from models import User, Cart, CartItem, Product
from authentication import get_current_user
from tortoise.expressions import F
router = APIRouter()
@router.post("/cart/add")
async def add_to_cart(
product_id: int, quantity: int, user: User = Depends(get_current_user)
):
product = await Product.get(id=product_id)
cart, _ = await Cart.get_or_create(user=user)
updated = await CartItem.filter(cart=cart, product=product).update(quantity=F('quantity') + quantity, price=product.new_price)
if updated == 0:
await CartItem.create(cart=cart, product=product, quantity=quantity, price=product.new_price)
return {"message": "Item added to cart"}