Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

408
Visualizações
Python peewee / fastapi get User without loading Items

So I followed this tutorial to kombine fastapi & peewee: link

And due to this tutorial i got those models (peewee):

class User(peewee.Model):
    email = peewee.CharField(unique=True, index=True)
    hashed_password = peewee.CharField()
    is_active = peewee.BooleanField(default=True)

    class Meta:
        database = db


class Item(peewee.Model):
    title = peewee.CharField(index=True)
    description = peewee.CharField(index=True)
    owner = peewee.ForeignKeyField(User, backref="items")

    class Meta:
        database = db

And those basemodels (fastapi):

class PeeweeGetterDict(GetterDict):
    def get(self, key: Any, default: Any = None):
        res = getattr(self._obj, key, default)
        if isinstance(res, peewee.ModelSelect):
            return list(res)
        return res


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


class ItemCreate(ItemBase):
    pass


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

    class Config:
        orm_mode = True
        getter_dict = PeeweeGetterDict


class UserBase(BaseModel):
    email: str


class UserCreate(UserBase):
    password: str


class User(UserBase):
    id: int
    is_active: bool
    items: List[Item] = []

    class Config:
        orm_mode = True
        getter_dict = PeeweeGetterDict

I have this to call the api:

database.db.connect()
database.db.create_tables([User, Item])
database.db.close()

app = FastAPI()

def get_db(db_state=Depends(reset_db_state)):
    try:
        database.db.connect()
        yield
    finally:
        if not database.db.is_closed():
            database.db.close()

@app.get("/users/", response_model=List[schemas.User], dependencies=[Depends(get_db)])
def read_users():
    return list(models.User.select()

This is the base. Now begins my problem / question:

If I call this request (GET "/users/"), I get the following JSON as a result (the data is imaginary its only about the structure)

[
    {
        "email": "123@test.com"
        "id": 1
        "is_active": 1
        "items": [
            {
                "title": "item1"
                "description": "placeholder"
                "id": "1"
                "owner_id": "1"
            }
        ]
    }
]

This is how it is supposed to be BUT i don't want it exactly like this. I want that I only get the user data, without its items.

So... my question:

How can I get the user data without loading the data of the items?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

There is a simple way to do that, response_model_exclude is exactly what you are looking for.

@app.get("/users/", response_model=List[schemas.User], response_model_exclude={"items"}, dependencies=[Depends(get_db)])
def read_users():
    return list(models.User.select()

Ref: FastAPI Response Model

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda