Creating Models

Models in RouteMQ define your database structure using SQLAlchemy's declarative syntax with async support.

Model Basics

Base Model Class

All models inherit from the SQLAlchemy Base class:

from sqlalchemy import Column, Integer, String, Float, DateTime, Text, Boolean
from core.model import Base
import time

class SensorReading(Base):
    __tablename__ = "sensor_readings"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    sensor_id = Column(String(50), nullable=False, index=True)
    sensor_type = Column(String(20), nullable=False)
    value = Column(Float, nullable=False)
    unit = Column(String(10))
    timestamp = Column(Float, nullable=False, default=time.time)
    
    def __repr__(self):
        return f"<SensorReading(sensor_id='{self.sensor_id}', value={self.value})>"

Model Directory Structure

Organize models in the app/models/ directory:

Column Types

Common Column Types

String Lengths

Choose appropriate string lengths for your use case:

Indexes and Constraints

Database Indexes

Add indexes for frequently queried columns:

Unique Constraints

Check Constraints

Relationships

Foreign Keys

One-to-Many Relationships

Many-to-Many Relationships

Model Methods

Instance Methods

Add custom methods to your models:

Class Methods

Add class-level query methods:

Model Examples

IoT Device Model

Alert Model

User Session Model

Model Registration

Importing Models

Models must be imported to be registered with SQLAlchemy:

Auto-discovery (Optional)

Create a model registry for automatic discovery:

Validation

SQLAlchemy Validators

Custom Validation Methods

Best Practices

Naming Conventions

  1. Table names: Use snake_case plural nouns (sensor_readings, device_statuses)

  2. Column names: Use snake_case (device_id, created_at)

  3. Model classes: Use PascalCase singular nouns (SensorReading, DeviceStatus)

Performance Tips

  1. Add indexes on frequently queried columns

  2. Use appropriate column types and sizes

  3. Define relationships carefully to avoid N+1 queries

  4. Use lazy loading for large datasets

Organization Tips

  1. One model per file for better maintainability

  2. Group related models in the same module if small

  3. Use consistent patterns across all models

  4. Document complex relationships and constraints

Next Steps

Last updated