table follow requires the id length of user

This commit is contained in:
2026-05-18 22:36:23 +08:00
parent a73b3cce26
commit d457c07f40
2 changed files with 23 additions and 3 deletions
+6 -1
View File
@@ -60,6 +60,11 @@ class AutoID:
_id_prefix_len = 3 # 前缀长度 _id_prefix_len = 3 # 前缀长度
_id_payload_len = 22 # 主体长度(ULID 转 Base62 最大约 22 位) _id_payload_len = 22 # 主体长度(ULID 转 Base62 最大约 22 位)
@classmethod
def id_length(cls) -> int:
"""返回当前类 ID 的总长度"""
return cls._id_prefix_len + cls._id_payload_len
@declared_attr @declared_attr
def id(cls): def id(cls):
# 运行时动态获取子类的 __tablename__ # 运行时动态获取子类的 __tablename__
@@ -74,4 +79,4 @@ class AutoID:
payload = gen_convex_payload(length=s_len) payload = gen_convex_payload(length=s_len)
return f"{prefix}{payload}" return f"{prefix}{payload}"
return Column(String(p_len + s_len), primary_key=True, default=id_factory) return Column(String(cls.id_length()), primary_key=True, default=id_factory)
+17 -2
View File
@@ -1,13 +1,28 @@
from typing import TYPE_CHECKING
from sqlalchemy import Column, DateTime, String, ForeignKey, UniqueConstraint from sqlalchemy import Column, DateTime, String, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func from sqlalchemy.sql import func
from .base import AutoID, Base from .base import AutoID, Base
# 只有在静态检查时才导入
# 运行阶段这段代码会被跳过,彻底避免循环导入
# 不确定是否用得上,但感觉这是个好习惯,尤其在模型之间有外键关系时
if TYPE_CHECKING:
from .user import User
class Follow(Base, AutoID): class Follow(Base, AutoID):
"""用户关注关系表""" """用户关注关系表"""
__tablename__ = "follows" __tablename__ = "follows"
follower_id = Column(String(32), ForeignKey("users.id", ondelete="CASCADE"), index=True) follower_id = Column(
followee_id = Column(String(32), ForeignKey("users.id", ondelete="CASCADE"), index=True) String(User.id_length()),
ForeignKey("users.id", ondelete="CASCADE"),
index=True
)
followee_id = Column(
String(User.id_length()),
ForeignKey("users.id", ondelete="CASCADE"),
index=True
)
created_at = Column(DateTime(timezone=True), server_default=func.now()) created_at = Column(DateTime(timezone=True), server_default=func.now())