blob: 041e263caf1fe2e49c52ca382952014aff4ec5e3 [file] [log] [blame] [edit]
from .users import User
from . import Base
from sqlalchemy import (
Column, Integer, String, Text, JSON, Enum,
TIMESTAMP, ForeignKey, Index, func, text
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
class Post(Base):
__tablename__ = 'posts'
__table_args__ = (
# 索引
Index('idx_posts_heat', 'heat'),
# MySQL 引擎、字符集、校对规则、表注释
{
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8mb4',
'mysql_collate': 'utf8mb4_general_ci',
'comment': '内容帖子表'
}
)
def to_dict(self):
return {
'id': self.id if self.id else None,
'user_id': self.user_id if self.user_id else None,
'topic_id': self.topic_id if self.topic_id else None,
'type': self.type if self.type else None,
'title': self.title if self.title else None,
'content': self.content if self.content else None,
'media_urls': self.media_urls if self.media_urls else None,
'status': self.status if self.status else None,
'heat': self.heat if self.heat else None,
'created_at': self.created_at.isoformat() if self.created_at else None,
'updated_at': self.updated_at.isoformat() if self.updated_at else None
}
id = Column(
Integer,
primary_key=True,
autoincrement=True,
comment='帖子ID'
)
user_id = Column(
Integer,
ForeignKey('users.id', ondelete='CASCADE'),
nullable=False,
index=True,
comment='作者ID'
)
topic_id = Column(
Integer,
ForeignKey('topics.id', ondelete='SET NULL'),
nullable=True,
index=True,
comment='所属话题ID'
)
type = Column(
Enum('text', 'image', 'video', 'document', name='post_type'),
nullable=False,
server_default=text("'text'"),
comment='内容类型'
)
title = Column(
String(255),
nullable=False,
comment='标题'
)
content = Column(
Text,
nullable=False,
comment='正文内容'
)
media_urls = Column(
JSON,
nullable=True,
comment='媒体资源URL数组'
)
status = Column(
Enum('draft', 'pending', 'published', 'deleted', 'rejected', name='post_status'),
nullable=False,
server_default=text("'draft'"),
comment='状态'
)
heat = Column(
Integer,
nullable=False,
server_default=text('0'),
comment='热度值'
)
created_at = Column(
TIMESTAMP,
nullable=True,
server_default=func.current_timestamp(),
comment='创建时间'
)
updated_at = Column(
TIMESTAMP,
nullable=True,
server_default=func.current_timestamp(),
onupdate=func.current_timestamp(),
comment='更新时间'
)
# 可选:与 User/Topic 模型的关系(需要在 User、Topic 中也定义 back_populates)
# user = relationship('User', back_populates='posts')
# topic = relationship('Topic', back_populates='posts')