Mapper映射的类无法为映射表组装任何主键列

时间:2019-07-29 18:28:11

标签: python sqlalchemy

sqlalchemy.exc.ArgumentError: Mapper mapped class PartCar->partcar could not assemble any primary key columns for mapped table 'partcar'
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship

Base = declarative_base()


class User(Base):
    __tablename__ = 'USER'

    user_id = Column(Integer)
    passport_number = Column(String(8), primary_key=True, nullable=False)
    user_email = Column(String(20), nullable=False)
    user_name = Column(String(20), nullable=False)

    carHave = relationship('Car', secondary='caruser')


class Car(Base):
    __tablename__ = 'car'

    car_number = Column(Integer, primary_key=True, nullable=False)

    userHave = relationship('User', secondary='caruser')
    partHave = relationship('Part', secondary='partcar')


class Part(Base):
    __tablename__ = 'part'

    part_name = Column(String(20), primary_key=True, nullable=False)

    carHave = relationship('Car', secondary='partcar')


class CarUser(Base):
    __tablename__ = 'caruser'

    user_passport_number = Column(String(8), ForeignKey('USER.passport_number'))
    car_number = Column(Integer, ForeignKey('car.car_number'))
    car_model = Column(String(20), nullable=False)


class PartCar(Base):
    __tablename__ = 'partcar'

    part_car_number = Column(Integer, ForeignKey('car.car_number'))
    part_name = Column(String(20), ForeignKey('part.part_name'))
    part_price = Column(Integer, nullable=False)

1 个答案:

答案 0 :(得分:2)

您的 PartCar表没有主键,为此sqlalchemy引发了错误。

Flask-SQLAlchemy需要主键,因为SQLAlchemy ORM requires a primary key

  

SQLAlchemy ORM为了映射到特定表而需要   至少是一个表示为主键的列。

     

大多数ORM要求对象定义某种主键   因为内存中的对象必须对应于唯一   数据库表中的可识别行。