Fastapi learning path (34) database multi table operation



Previously, we shared the operation based on a single database table. We also designed a cross table when designing the database. We can take a look at the database design.


class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
    items = relationship("Item", back_populates="owner")

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey(""))
    owner = relationship("User", back_populates="items")

Let’s take a look at how to create the corresponding pydantic model.

class ItemBase(BaseModel):
    title: str
    description: Optional[str] = None

class ItemCreate(ItemBase):

class Items(ItemBase):
    id: int
    owner_id: int

    class Config:
        orm_mode = True

In fact, there is nothing special here, just some simple configurations. But we need to update the pydantic model


from pydantic import BaseModel
from typing import List,Optional
class Users(UserBase):
    Response model:
    id:email: is_ Active and set ORM_ Mode compatible
    id: int
    is_active: bool
    items: List[Items] = []
    class Config:
        orm_mode = True

Add adaptation for items. We also need to transform the place where we operate the database.

def get_item(db: Session, skip: int = 0, limit: int = 100):
    return db.query(Item).offset(skip).limit(limit).all()

#New user's item
def create_user_item(db: Session, item: ItemCreate, user_id: int):
    db_item = Item(**item.dict(), owner_id=user_id)
    return db_item

Let’s add two interfaces. One is to create an item and the other is to obtain an item

#All items
@app.get("/items/", response_model=List[Items])
def read_items(skip: int = 0, limit: int = 0, db: Session = Depends(get_db)):
    items = get_item(db=db, skip=skip, limit=limit)
    return items

#Create user's item"/users/{user_id}/items", response_model=Items)
def create_item_user(user_id: int, item: ItemCreate, db: Session = Depends(get_db)):
    return create_user_item(db=db, item=item, user_id=user_id)

Let’s debug it.



Let’s check all the items



Let’s develop an interface to query users’ items.

#Encapsulate operation database
def get_user_item(db:Session,userid:int):
    return  db.query(Item).filter(Item.owner==user).offset(1).limit(1).all()
#Encapsulated interface"/user/item/{user_id}",response_model=List[Items])
def get_user_items(user_id:int,db:Session=Depends(get_db)):
    return get_user_item(db=db,userid=user_id)

Let’s test back


We have implemented a simple multi table query.

The article is first published in the official account. Welcome to pay attention.