Использование 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
If this is a general representation of #GenZ then they are genuinely retarded, while ironically still going on to further indoctrination. Don't expect an uprising imminently!
https://youtu.be/rG92wMoJypc
👦👧Generation Z will outnumber Millennials by 2019
And 40% of #GenZ consider working wifi more important than working bathrooms 😐
🚀@PerspectiveIX via WEF
❓Which one do YOU consider more important?
Super riassuntone di Hagi su ciò che è accaduto in Nepal in questo 2026.
Dalla rivolta della genZ agli equilibrismi dei potenti stati vicini.
#Nepal#genz
🦣 Segui il Capibara 🦧
📊 Gen Z is Still on Facebook
Think you cannot target #GenZ on #Facebook? Think again!
Socialbakers' data shows that this generation is giving brands as much love as #Millennials!
🚀@PerspectiveIX via Socialbakers.
⚡️Generation Z & Their Love for Aesthetic Boards
#GenZ is often referred to as one of the most unique, values-driven generations. They see identity as fluid and care about social impact, with 56% considering themselves socially conscious, according to #Pinterest.
There are over 37 million aesthetic related boards on Pinterest, with Gen Z’ers searching for “aesthetic” 447% more than #Millennials. Through aesthetic boards like witch, grunge and love, Gen Z is finding their identity.
- Witch Aesthetic +281%, 3.1X more than millennials
- Grunge Aesthetic +262%, 6.3X more than millennials
- Love Aesthetic +351%, 2.6X more than millennials
- Art Aesthetic +353%, searching 3.3X more than millennials
- Writing Aesthetic +241%, searching 7.0X more than millennials
As Gen Z curates these boards to find their inner selves, they provide a unique look into emerging subcultures and passions.
❗️Generation Z or Gen Z, also known by a number of other names, is the demographic cohort after the Millennials. There are no precise dates for when this cohort starts or ends, but demographers and researchers typically use the mid-1990s to mid-2000s as starting birth years. There is little consensus regarding ending birth years.
🚀@PerspectiveIX via Pinterest .
❓When were you born?
Are adulting responsibilities creeping up on you? 🕷️
This Halloween, it’s time we face these Gen Z scaries head-on – filing taxes without a clue! But don’t worry, IRAS has all the digital spells (aka explainers and resources) to help you through! No tricks, just treats for your financial future. 🧙♀️
🎃 Find out more at go.gov.sg/taxbytes
#halloween#genz#irassg
🤳The Story of Stories
According to a VidMob survey conducted among a thousand 16-24-year-olds in the US, #Snapchat (73%) edges #Instagram (70%) for consumption of Stories. However, the gap in #GenZ's content creation for Stories is a lot bigger on these platforms where Snapchat (58%) is way ahead of Instagram (39%).
For #Millennials, however, the story is a bit different. According to the accompanying survey of a thousand 25-34-year-olds, they seem to prefer Instagram (58%) instead of Snapchat (53%) for story consumption. But just like their younger counterparts, Snapchat (34%) is their platform of choice when it comes to creating stories compared to Instagram (31%) or #Facebook (20%).
🚀@PerspectiveIX
via MarketingCharts: prs.pctvix.co/2MTD6e9
❓Where do YOU WATCH Stories?
📱🇺🇸GENERATION Z PANICS OVER WAR DRAFT RUMORS
🔹 TikTok flooded with videos of young Americans researching how to avoid military service as Iran conflict escalates ⚡
🔹 Google searches for "draft exemptions" spike 500% in past two weeks 📈
🔹 Campus advisors overwhelmed with students asking about graduate school deferrals and medical exemptions 🎓
🔹 Dating apps see surge in profiles mentioning "no military guys" as relationships become strategic 💔
🔹 Mental health hotlines report increase in anxiety calls from 18-25 year olds about potential conscription 📞
This generation is NOT here for another Vietnam 😬🔥
#USNews#GenZ#socialMedia#anxiety
@america
Zoomers Embrace NEET Trend in Southern Europe — Not in Education, Employment, or Training
A new trend among Zoomers (Generation Z) is gaining traction: NEET, which stands for "Not in Education, Employment, or Training." This trend reflects a significant number of young people opting out of traditional career paths.
In Southern Europe, one in five Zoomers is reportedly following this trend. Experts attribute this shift to growing pessimism about career prospects and earnings. Many young people have concluded that there is no point in striving for traditional employment or education paths, given the perceived lack of opportunities and financial stability.
Subscribe: @nido_russia
#genz#zoomers#europe#nidorussia
Roblox - это новый Vogue
#GenZ#Roblox#тренды#digital
Аналитики Roblox нплохо разбираются во всем, что касается моды, тредов и предпочтений потребителей поколения Z, а всё потому, что они мониторят интересы и активность 200-милионной аудитории платформы
Roblox второй год подряд выпускает годовой отчет «Тренды в сфере самовыражения, моды и красоты в digital». С помощью больших данных анализируют поведение пользователей и формируют гипотезы, а затем опрашивают 1500 респондентов, чтобы свои изыскания опровергнуть или подтвердить
Вот основные инсайты:
1) Тема самовыражения и презентации игрока в цифровой важнее, чем внешний вид и стиль в реальном мире.
Так в 2022 году 42% респондентов заявили, что стиль и внешний вид игрового аватара для них важнее, чем самопрезентация в реальном мире. За год число тех, кому digital важнее реала увеличилось до 56%
2) Респоденты в отчете Roblox сообщили, что отдают предпочтение тем брендам при "прокачке" цифрового аватара, которые знают из реальной жизни.
Для 47% фактор узнаваемости или статуса бренда является чрезвычайно важным.
3) Переплетение физического и цифрового миров в сфере fashion всегда присутствовало в картине мира потребителей. 43% говорят, что их интересуют такие вещи, которые можно носить как в метавселенной, так и в реальном мире.
84% представителей Gen Z заявили, что они рассмотривают покупку продукции бренда в реальном мире, если у них есть что-то от этой марки в формате digital.
4) Цифровые аватары влияют на стиль людей в реальной жизни.
84% отметили, что их реальный гардероб "вдохновлен" стилем аватара в игре. Кроме того, каждый четвертый пользователь заявил, что очень хочет выглядеть так же как аватар.
5) Готовность тратить деньги на digital моду в игре - еще один интересный фактор. Почти половина респондентов заявила, что им достаточно бюджета до 10 долларов в месяц, который можно потратить на цифровую одежду, 19% готовы тратить до 20 долларов, а 18% от 50 до 100 долларов.
Текст отчета можно посмотреть по ссылке
#аналитика#прямаяречь#чтоониговорят#GenZ
Яндекс Дзен провел исследование сленговых слов, популярных среди россиян в возрасте от 14 до 25 лет(Gen Z)
Что в топе?
«Форсить», «краш» и POV (точка зрения/ ИМХО).
Запишите в ваши молескины еще 3 любопытных вывода с авторскими (моими) комментариями:
1️⃣ Пятая часть опрошенных (21%) легко определяет «кто здесь зумер, а кто бумер» а кто умер в соцсетях по использованию эмодзи типа 👉👈
И да 15% респондентов считают, что те, кто родился с 1981 по 1996 год, новый язык интернет-культуры не понимают.
Ваша редакция со своими стрелочками-пальчиками уверенно болтается на грани Gen X / Gen Y
2️⃣ 19% аудитории 14-25 летних узнает друг друга по кодовым фразам и аббревиатурам типа POV, main character, man/woman moment, «ситуация сюр», sigma, dead inside.
Мемность есть и у фраз из популярных видео: «Если б мы знали, что это такое, но мы не знаем, что это такое», «Ты не понимаешь, это другое» и «На чилле, на расслабоне».
3️⃣ Самые популярные эмодзи:
😭 (50%)
🤡 (46%) = тупой или глупый поступок.
👀 (22%) = «оч. интересно, продолжай» (Gen Y, это я перевела термин на мемы нашего поколения - СЩ)
Эмодзи чаще отправляют женщины (54% в сообщениях ставят 3 и более смайликов), чтобы передать эмоции. А у парней чуть иначе: только 35% делают это.
Автор канала говорит «фОрсить» (хотя слово знаю с XX века, тогда ударение было на другой слог - «форсИть» и оно означало «модничать / выпендриваться»), краш. А вот POV знаю, но не применяю потому что для меня это прям adult контекст по написанию и я, судя по комментариям, не улавливаю смысл…🤦♀
А у вас как дела с эмодзи и современным сленгом?
И да, что по трактовке POV?