Web TippsUse custom web fonts in Google Sheets charts(08.09.2026 um 17:05 Uhr)
Web TippsIntroducing the new 1Password App for Google Chat(08.09.2026 um 18:02 Uhr)
Web TippsUse custom web fonts in Google Sheets charts(08.09.2026 um 17:05 Uhr)
Web TippsIntroducing the new 1Password App for Google Chat(08.09.2026 um 18:02 Uhr)

🔧 Programmierung 🕛 vor 1 Jahr 3 Min Lesezeit
0

Modularizing SQLAlchemy Models with Mixins and Annotations

↗ Quelle (dev.to)
🗣️ Stimme:

provide reusable logic or fields for models. Let's define a TimestampMixin that automatically adds created_at and updated_at fields to any model that inherits from it.

 

File: timestamp_mixin.py




CODE
from datetime import datetime
from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import declared_attr

class TimestampMixin:
@declared_attr
def created_at(cls):
return Column(DateTime, default=datetime.utcnow, nullable=False)

@declared_attr
def updated_at(cls):
return Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)









Explanation



  • @declared_attr: Ensures that the attributes are dynamically added to the inheriting models.

  • default and onupdate: Automatically set timestamps for creation and updates.



 






Defining Common Annotations



SQLAlchemy’s Annotated types, available via Python’s typing.Annotated, let you define reusable column properties. For example, you can define a UUID primary key or a String column with specific constraints.

 

File: common_annotations.py




CODE
from typing import Annotated
from uuid import uuid4
from sqlalchemy import String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import mapped_column

uuid4pk =
mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid4, nullable=False)
]

name = Annotated[
str,
mapped_column(String(30), nullable=False)
]









Explanation



  • UUID Primary Key: The uuid4pk annotation defines a universally unique identifier for primary keys.

  • Name Column: The name annotation ensures a String column with a maximum length of 30 characters and no NULL values.



 






Building Models with Mixins and Annotations



Using the mixins and annotations, we can define models that inherit shared behavior and properties while keeping the implementation concise and readable.

 

File: user.py




CODE
from sqlalchemy.orm import Mapped
from sqlalchemy.ext.declarative import declarative_base
from mixins import TimestampMixin
from annotations import uuid4pk, name

Base = declarative_base()

class User(Base, TimestampMixin):
__tablename__ = 'users'

id: Mapped[uuid4pk]
first_name: Mapped[name]
last_name: Mapped[name]









Explanation



  • Declarative Base: The Base serves as the foundation for all SQLAlchemy models.



 






Benefits of This Approach



1. Clear Separation of Concerns




  • timestamp_mixin.py: Contains reusable logic (e.g., timestamps).

  • common_annotations.py: Defines common column properties (e.g., UUIDs, strings).

  • user.py: Combines these building blocks into concrete models.



2. Ease of Maintenance




  • If it is needed to change how timestamps work or update column constraints, it is only needed to modify the timestamp_mixin.py or common_annotations.py files. The changes automatically reflect across all dependent models.



3. Scalability




  • As project grows, this structure makes it easier to add new behaviors or field types without introducing redundancy.



   






Final Thoughts



Modularizing models with SQLAlchemy's mixins and annotations is a good strategy for handling shared functionality and properties. This approach not only reduces duplication but also aligns with best practices for clean, maintainable code.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
Use custom web fonts in Google Sheets charts
2 Quellen
Introducing the new 1Password App for Google Chat
1 Quelle
Context-aware access controls are available for Gemini Enterprise in the Admin console
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Modularizing SQLAlchemy Models with Mixins and Annotations

Thematisch verwandte Begriffe: Modularizing, SQLAlchemy, Models, with · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...