Add get by field

This commit is contained in:
Edkar Chachati
2024-01-15 16:12:09 -04:00
parent cd233609bf
commit a87f364e94
3 changed files with 42 additions and 8 deletions

View File

@ -45,13 +45,12 @@ class CRUDManager:
"""
self.db = db or self.db
query = select(self.model).where(self.model.id == pk)
obj = self.db.exec(query).one_or_none()
if obj is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"{self.model} with ID: {pk} Not Found",
)
return obj
if obj := self.db.exec(query).one_or_none():
return obj
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"{self.model} with ID: {pk} Not Found",
)
def get_by_ids(self, ids: list[int], db: Session = None) -> list[ModelType]:
"""
@ -73,6 +72,32 @@ class CRUDManager:
query = select(self.model).where(self.model.id.in_(ids))
return self.db.exec(query).all()
def get_by_field(self, field: str, value: str, db: Session = None) -> ModelType:
"""
The function retrieves a model object from the database based on a
field and a value.
Arguments:
* `field`: The parameter `field` is a string that represents the name
of a field in the database table.
* `value`: The parameter `value` is a string that represents the value
of a field in the database table.
Returns:
The `get_by_field` method is returning an object of type `ModelType`.
"""
self.db = db or self.db
query = select(self.model).where(getattr(self.model, field) == value)
if obj := self.db.exec(query).one_or_none():
return obj
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"{self.model} with {field}: {value} Not Found",
)
def list(self, query: QueryLike = None, db: Session = None) -> list[ModelType]:
"""
The function returns a list of all the records in the database that