我正在尝试通过 ORM 将另外两个表添加到已经存在的 MySQL 数据库中。我要添加的表是DataInfo
和Project
,已经存在的表是User
。如您所见,我的Project
表有一个 ForeignKey 到User
表,但是每当我运行代码时,我都会收到错误消息sqlalchemy.exc.ArgumentError: Mapper mapped class User->d_users could not assemble any primary key columns for mapped table 'd_users'
。我在网上遵循了一些教程,但无法解决我的问题。
这是我的 models.py 文件。
from sqlalchemy import Column, ForeignKey, Integer, String, Date, MetaData, Table
from sqlalchemy.orm import relationship
from .database import Base
from datetime import datetime
class User(Base):
__tablename__ = "d_users"
class DataInfo(Base):
__tablename__ = "d_data_info"
id = Column(Integer, primary_key=True, index=True)
isURL = Column(Integer, index=True)
dataSource = Column(String(100), index=True)
dateCreated = Column(Date, index=True, default=datetime.date(datetime.now()))
projectId = Column(Integer, ForeignKey("d_ml_projects.projectId"))
data_for_project = relationship("Project", back_populates="data")
class Project(Base):
__tablename__ = "d_ml_projects"
projectId = Column(Integer, primary_key=True, index=True)
projectTitle = Column(String(200), index=True)
projectDescription = Column(String(550), index=True)
problemType = Column(String(15), index=True)
classLabel = Column(String(100), index=True)
userId = Column(Integer, ForeignKey("d_users.id"))
data = relationship("DataInfo", back_populates="data_for_project")
数据库.py:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://martin:password@localhost/hope"
engine = create_engine(
SQLALCHEMY_DATABASE_URL
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
我DESCRIBE d_users
来自 MySQL;
+-------------------+--------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+-------------------+-----------------------------+
| id | varchar(36) | NO | PRI | NULL | |
| oAuthId | varchar(48) | NO | UNI | NULL | |
| oAuthType | varchar(20) | YES | | NULL | |
| firstName | varchar(50) | YES | | NULL | |
| secondName | varchar(50) | YES | | NULL | |
| city | varchar(50) | YES | | NULL | |
| phone | varchar(20) | YES | | NULL | |
| email | varchar(100) | YES | UNI | NULL | |
| profileLink | varchar(300) | YES | | NULL | |
| profilePic | varchar(300) | YES | | NULL | |
| status | varchar(10) | YES | | NULL | |
| notificationToken | text | YES | | NULL | |
| password | varchar(64) | YES | | NULL | |
| confirmed | tinyint(1) | YES | | 0 | |
| notes | text | YES | | NULL | |
| created_timestamp | timestamp | NO | | CURRENT_TIMESTAMP | |
| updated_timestamp | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------------+--------------+------+-----+-------------------+-----------------------------+