<%
    model_name = entity.name.capitalize()
    relations = generator._process_relations(entity)
%>
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.orm import relationship
from ..database import Base

class ${model_name}(Base):
    """
    ${entity.description or model_name + ' 模型'}
    对应数据库表: ${entity.name.lower()}s
    """
    __tablename__ = "${entity.name.lower()}s"

    # 主键字段
    % if not any(field['primary_key'] for field in entity.fields):
    id = Column(Integer, primary_key=True, index=True, doc="主键ID")
    % endif
    
    % for field in entity.fields:
    ## 字段定义: ${field['name']}
    ${field['name']} = Column(
        ${'String' if field['type'] == 'String' else 'Integer' if field['type'] in ('Long', 'Integer') else 'Boolean' if field['type'] == 'Boolean' else 'DateTime' if field['type'] == 'DateTime' else 'String'},
        % if field['type'] == 'String' and 'length' in field:
        length=${field['length']},
        % endif
        % if 'default' in field:
        default=${field['default']},
        % endif
        % if 'primary_key' in field:
        primary_key=True,
        % endif
        % if 'unique' in field and field['unique']:
        unique=True,
        % endif
        % if 'nullable' in field and not field['nullable']:
        nullable=False,
        % endif
        % if 'index' in field and field['index']:
        index=True,
        % endif
        doc="${field['description'] or field['name'] + '字段'}"
    )
    % endfor
    
    # 关系定义
    % for rel in relations:
    ## ${rel['type']} 关系: ${rel['name']}
    % if rel['type'] == 'one-to-many':
    ${rel['name']} = relationship(
        "${rel['target'].capitalize()}",
        back_populates="${rel['reverse_name']}",
        doc="${rel['description'] or model_name + '的' + rel['name']}"
    )
    % elif rel['type'] == 'many-to-one':
    ${rel['name']}_id = Column(Integer, ForeignKey("${rel['target']}s.id"))
    ${rel['name']} = relationship(
        "${rel['target'].capitalize()}",
        back_populates="${rel['reverse_name']}",
        doc="${rel['description'] or '关联的' + rel['target']}"
    )
    % elif rel['type'] == 'many-to-many':
    ${rel['name']} = relationship(
        "${rel['target'].capitalize()}",
        secondary="${rel['through']}",
        back_populates="${rel['reverse_name']}",
        doc="${rel['description'] or model_name + '的多对多关联'}"
    )
    % endif
    % endfor