Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

407
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda