mirror of
https://github.com/creyD/creyPY.git
synced 2026-04-12 19:30:30 +02:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa7a1c8a61 | ||
| 5a7e1776db | |||
| 4c25d91e18 |
@@ -2,6 +2,14 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 1.2.3
|
||||
|
||||
- Added option to specify lookup_column for get_object_or_404
|
||||
|
||||
## 1.2.2
|
||||
|
||||
- Added order_by method
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- Added headers to testing
|
||||
|
||||
@@ -10,8 +10,10 @@ from .models.base import Base
|
||||
T = TypeVar("T", bound=Base)
|
||||
|
||||
|
||||
def get_object_or_404(db_class: Type[T], id: UUID | str, db: Session, expunge: bool = False) -> T:
|
||||
obj = db.query(db_class).filter(db_class.id == id).one_or_none()
|
||||
def get_object_or_404(
|
||||
db_class: Type[T], id: UUID | str, db: Session, expunge: bool = False, lookup_column: str = "id"
|
||||
) -> T:
|
||||
obj = db.query(db_class).filter(getattr(db_class, lookup_column) == id).one_or_none()
|
||||
if obj is None:
|
||||
raise HTTPException(status_code=404, detail="The object does not exist.")
|
||||
if expunge:
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
from typing import Callable
|
||||
|
||||
from pydantic.json_schema import SkipJsonSchema
|
||||
from sqlalchemy import asc, desc
|
||||
from sqlalchemy import String, asc, cast, desc
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.sql.selectable import Select
|
||||
|
||||
|
||||
@@ -9,7 +10,16 @@ def order_by(order_by: str | SkipJsonSchema[None] = None) -> Callable[[Select],
|
||||
def _order_by(query: Select) -> Select:
|
||||
if order_by:
|
||||
direction = desc if order_by.startswith("-") else asc
|
||||
query = query.order_by(direction(order_by.lstrip("-")))
|
||||
column_name = order_by.lstrip("-")
|
||||
|
||||
# Get the column from the query
|
||||
for column in query.inner_columns:
|
||||
if column.key == column_name:
|
||||
# If the column is a UUID, cast it to a string
|
||||
if isinstance(column.type, UUID):
|
||||
column = cast(column, String)
|
||||
query = query.order_by(direction(column))
|
||||
break
|
||||
return query
|
||||
|
||||
return _order_by
|
||||
|
||||
Reference in New Issue
Block a user