Skip to content

Commit

Permalink
Fix currency validation & serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn committed Nov 13, 2023
1 parent fba1110 commit 660e2a8
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import field_serializer
from pydantic import field_validator
from sqlalchemy_utils import Currency

from app.enums import PriceLocationOSMType

Expand All @@ -16,21 +18,35 @@ class UserBase(BaseModel):


class PriceCreate(BaseModel):
model_config = ConfigDict(from_attributes=True)
model_config = ConfigDict(from_attributes=True, arbitrary_types_allowed=True)

product_code: str
price: float
currency: str = "EUR"
currency: str | Currency = "EUR"
location_osm_id: int
location_osm_type: PriceLocationOSMType
date: date

@field_validator("currency")
def currency_is_valid(cls, v):
try:
return Currency(v).code
except ValueError:
raise ValueError("not a valid currency code")

@field_validator("location_osm_id")
def location_osm_id_must_be_positive(cls, v):
if v <= 0:
raise ValueError("must be positive")
return v

@field_serializer("currency")
def serialize_currency(self, currency: Currency, _info):
if type(currency) is Currency:
return currency.code
return currency


class PriceBase(PriceCreate):
# owner: str
created: datetime

0 comments on commit 660e2a8

Please sign in to comment.