Skip to content

Instantly share code, notes, and snippets.

@Butch78
Last active May 14, 2022 21:22
Show Gist options
  • Save Butch78/dfefe4d404f84b510648f7e86cf356d3 to your computer and use it in GitHub Desktop.
Save Butch78/dfefe4d404f84b510648f7e86cf356d3 to your computer and use it in GitHub Desktop.
Pydantic Query Object
# -------------------------------------------------
# BaseQuery Model
# -------------------------------------------------
# The Base schema for query objects
class BaseQuery(BaseModel):
skip: int = Query(0, title='Skip', description='How many pages to skip')
limit: int = Query(100, title='Limit',
description='The limit of results to be returned')
@validator('*')
def check_values(cls, v, field: ModelField):
if v:
try:
field.populate_validators()
return v
except Exception as error:
raise HTTPException(
422, detail=f'Query is in the wrong format: {error}')
class Config:
use_enum_values = True
class OrganisationQuery(BaseQuery):
name: str = Query(None, title='Name',
description='The Name of the Organisation.')
abbreviation: str = Query(None, title='Abbreviation',
description='The Abbreviation of the Organisation.')
type: Optional[OrganisationEnum] = Query(None, title='Organisation Type',
description='What type of organisation ie University or Industry.')
# Example
@router.get('', response_model=List[OrganisationOut])
def get_organisations(db: Session = Depends(get_postgres_db),
queryParams: OrganisationQuery = Depends(OrganisationQuery)) -> Any:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment