Использование Pydantic сегодня стало нормой, и это правильно. Но иногда на ревью вижу, что используют его не всегда корректно.
Например, метод BaseModel.model_dump() по умолчанию не преобразует стандартные типы, такие как datetime, UUID или Decimal, в простой сериализуемый для JSON вид. Тогда пишут кастмоный сериализатор для этих типов чтобы функция json.dump() не падала с ошибкой.
import uuid
from datetime import datetime
from decimal import Decimal
from uuid import UUID
from pydantic import BaseModel
class MyModel(BaseModel):
id: UUID
date: datetime
value: Decimal
obj = MyModel(
id=uuid.uuid4(),
date=datetime.now(),
value='1.23'
)
print(obj.model_dump())
# не подходит для json.dump
# {
# 'id': UUID('4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1'),
# 'date': datetime.datetime(2025, 12, 12, 12, 12, 12, 111111),
# 'value': Decimal('1.23')
# }
# добавляем свой кастомный сериализатор
json.dumps(obj.model_dump(), cls=MySerializer)
# {
# 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1',
# 'date': '2025-12-12T12:12:12.111111',
# 'value': '1.23'
# }
В данном случае класс MySerializer обрабатывает datetime, UUID и Decimal. Например так:
class MySerializer(json.JSONEncoder):
def default(self, o):
if isinstance(o, Decimal):
return str(o)
elif isinstance(o, datetime):
return o.isoformat()
elif isinstance(o, UUID):
return str(o)
return super().default(o)
Специально для тех, кто всё еще так делает - в этом нет необходимости!
Pydantic может это сделать сам, просто нужно добавить параметр mode="json".
json.dumps(obj.model_dump(mode="json"))
# {
# 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1',
# 'date': '2012-12-12T12:12:12.111111',
# 'value': '1.23'
# }
#pydantic#libs
✅Mark your calendar for exciting AMA!
Analyzing 2025's Biggest Opportunity 🔮
Join us today at 12 PM UTC with @CyberChargeJoe ,the Co-Founder of #CyberCharge🔋
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🎄The XMAS holiday season is here!🎁
#CyberCharge Wish you a holiday full of happiness and Gem in bag! 💎
Unlock up to 1500 USDT Gift
📱Join here:https://t.me/CyberChargeGroup
✨Power up,Earn More
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Congrats 🎊CyberCharge Whitelist Event Ended Successfully!🔚
🔋You’ll enjoy a increase in charger revenue and have first access to profit sharing from the mining pool.⚡️CyberCharge orders are processing ,will be shipped over the next 30 days📆
#Cybercharge Brings the power of web3 charging and mining together!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🚆 The $GOUT train is on the move, and so are your chances to earn! Complete your first charge on #CyberCharge & share 1 MILLION $GOUT! 🤑
It’s easy:
🐦 Follow us & @GOUTCoin
🔋 Charge with the app + comment your APP ID below!
🔁 RT + Tag 2 friends
The market is heating up fast 🔥and so is the reward pool.
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🐾Meet AI Doggy, your loyal companion on the #CyberCharge journey! 🐕
✨Buy, grow, and earn with your digital pet
🔋Keep its health >50% for max mining rewards
💎Boost its value as you nurture it
⚠️Careful—if health hits 0, it’s game over!
Get Ready: https://link.medium.com/qzA4cxdp6Ob
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
↗️ROI So Quick, You’ll Blink Twice!
🔋Charging your devices is now a revenue stream. #CyberCharge makes it REAL with fast returns. Watch how you can earn in record time! 📽
💎Apply for the whitelist with Gem Shards in the Mini App today!
👉http://t.me/CyberChargeBot/whitelist
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🎉Celebrate our partnership with @arbitrum!🎉
To join:
1️⃣RT & Like this post
2️⃣Comment with your BEP20 wallet address and #CyberCharge TG ID
⚡️20 USDT x 5 winners! ⚡️
Get ready to Charge-to-Earn with CyberCharge on arbitrum! 💙🧡
🏆Winners announced in 3 days—don’t miss out! 🚀
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🔋CyberCharge x Movement is here!
⚡️By combining @movementlabsxyz ’s platform with #CyberCharge’s Charge to Earn technology, we’re making every charge count.
Now, users can earn rewards simply by staying powered up, all within a secure and engaging digital ecosystem.
Stay tuned for more!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🚀CyberCharge x EMC Partnership!⚡️We're thrilled to team up with@EMCprotocol to revolutionize blockchain-powered energy solutions!
EMC is a leading AI & DePIN platform that bridges the computing power network and decentralized AI applications!
🔋With the world’s first DePIN Charge-to-Earn (C2E) Network, #CyberCharge brings the power of charging and mining together!
Stay tuned for exciting updates as we unlock new paths for sustainable energy. 🌱
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Global electricity usage is spiking after decades of stable demand. Now CyberCharge tackle the sustainable energy challenge. But how to earn your ticket to the next-gen of energy networks?
🎬 NEW VIDEO DROP: How to Earn with #CyberCharge!
🎁GIVEAWAY
We’re giving away 5 $USDT to 10 lucky winners!
1️⃣Follow & RT
2️⃣Open the link 👉t.me/CyberCharge copy your TG ID, and paste it here.
3️⃣Screenshot your favorite part of the video and post it below!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🔋Ready to charge up your earnings? 💥
🤑Join the Charge-to-Earn event with #CyberCharge, where EVERYONE wins 100% guaranteed USDT rewards!
💰Earn NOW
🔗http://t.me/daily_gifts_en/74
Don’t miss out, it’s that simple: complete tasks & earn!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
👋Hey #CyberCharge mini APP users! We’ve rolled out some cool new updates:
✨Home upgraded with smooth new animations.
🛑 "Withdraw" button in My Assets now highlighted with extra safety prompts.
🎁Task interface refreshed: updated task lists and Mystery Box rewards shown per task!
💎Invite friends and earn even more Gem Shards!
🌐Global broadcasts—stay informed anytime, anywhere.
Update now for a smoother, safer experience!
🔋t.me/CyberChargeBot
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube