Add New Item to Inventory Functionality

  • Share this:

Code introduction


This function is used to add a new item to the inventory. It first retrieves or creates an inventory document, then creates a new item instance and adds it to the inventory.


Technology Stack : Beanie, Pydantic

Code Type : Function

Code Difficulty : Intermediate


                
                    
import beanie
from pydantic import BaseModel
import random
from typing import List

class Item(BaseModel):
    name: str
    quantity: int

class Inventory(beanie.Document):
    items: List[Item]

    meta = {
        "collection": "inventory"
    }

def add_item_to_inventory(item_name: str, quantity: int):
    # This function adds an item to the inventory
    inventory = Inventory.get_or_create()
    new_item = Item(name=item_name, quantity=quantity)
    inventory.items.append(new_item)
    inventory.save()

# Example usage:
# add_item_to_inventory("Apples", 50)