SQL Алхимия Вставить данные в отношение «Многие ко многим» - PullRequest
1 голос
/ 07 февраля 2020

У меня есть 3 табличных объявления в SQL Алхимия, как показано ниже, чтобы облегчить отношения многие ко многим



BusLink = Table(
    "BusLink",
    DB.metadata,
    Column("component_id", String(36), ForeignKey("Bus.componentId")),
    Column("algorithm_id", Integer, ForeignKey("Algorithm.algorithmId")),
)

class Bus(DB):

    __tablename__ = "Bus"

    component_id = Column("componentId", String(36), nullable=False, primary_key=True)
    end_client_id = Column("endClientId", String(50), nullable=False)
    end_client_type = Column("endClientType", String(50), nullable=False)
    component_type = Column("componentType", String(50), nullable=True)
    description = Column("description", Text, nullable=True)
    size = Column("size", Integer, nullable=True)

    file_name = Column("fileName", String(50), nullable=True)
    file_path = Column("filePath", String(50), nullable=True)
    file_hash = Column("fileHash", String(50), nullable=True)

    verified_date = Column("verifiedDate", DateTime, nullable=False, primary_key=True, default=datetime.utcnow)

    algorithm = relationship(
        "Algorithm",
        secondary=BusLink,
        backref=backref("Algorithm", lazy="dynamic"),
        cascade="all, save-update",
    )

    # Stores active status of a component
    active = Column("active", Boolean, default=True)

class Algorithm(DB):

    __tablename__ = "Algorithm"

    algorithm_id = Column("algorithmId", Integer, nullable=False, primary_key=True, autoincrement=True)

    algorithm_type = Column("algorithmType", String(50), nullable=False, unique=True)
    supports_seed = Column("supportsSeed", Boolean, nullable=False)
    supports_salt = Column("supportsSalt", Boolean, nullable=False)
    supports_offset = Column("supportsOffset", Boolean, nullable=False)

    bus = relationship(
        "Bus", secondary=BusLink,
        cascade="all, save-update"
    )

    active = Column("active", Boolean, default=True)


Мне нужно назначить уже созданные алгоритмы при сохранении шины.

# Creating 3 algorithms -> im using the following code
 async def save_data(self, **kwargs):
        """
        Saves an algorithm object and returns
        """
        try:
            with BUSDB() as db:
                results = (
                    db.session.query(Algorithm)
                    .filter(Algorithm.algorithm_type == kwargs["algorithm_type"], Algorithm.active == True)
                    .first()
                )
                if results:
                    return {"Error": f"Algorithm {kwargs['algorithm_type']} already exits"}

                results = (
                    db.session.query(Algorithm)
                    .filter(Algorithm.algorithm_type == kwargs["algorithm_type"], Algorithm.active == False)
                    .first()
                )

                if results:
                    db.session.query(Algorithm).filter(
                        Algorithm.algorithm_type == kwargs["algorithm_type"], Algorithm.active == False
                    ).update({Algorithm.active: True})

                    db.session.commit()

                    data = data_to_dict(
                        db.session.query(Algorithm).filter(Algorithm.algorithm_id == kwargs["algorithm_id"]).first()
                    )
                    data.pop("active")
                    return data

                data = Algorithm(**kwargs)
                db.session.add(data)
                db.session.commit()
                db.session.refresh(data)

                data = data_to_dict(data)
                data.pop("active")
                return data


Мне нужно назначить один или несколько алгоритмов при создании объекта Bus. Для этого у меня есть следующий код

    async def save_data(self, **kwargs):
        component_id = kwargs["component_id"]
        try:
            with BUSDB() as db:


                bus_object = Bus(
                    component_id=component_id,
                    component_type=kwargs.get("component_type"),
                    description=kwargs.get("description"),
                    size=kwargs.get("size"),
                    file_name=kwargs.get("file_name"),
                    file_path=kwargs.get("file_path"),
                    file_hash=kwargs.get("file_hash"),
                )

                # Issue Lies here
                for data in kwargs["algorithm"]:
                    bus_object.algorithm.append(
                        Algorithm(
                            algorithm_id=data["algorithmId"],
                            algorithm_type=data["algorithmType"],
                            supports_offset=data["supportsOffset"],
                            supports_salt=data["supportsSalt"],
                            supports_seed=data["supportsSeed"],
                        )
                    )

                db.session.add(bus_object)
                db.session.commit()

            return {"Success": True}

        except Exception as e:
            db.session.rollback()
            raise e

Приведенный выше код пытается создать новый объект Algorithm, даже если он доступен. Как исправить эту проблему, чтобы использовать уже доступный объект алгоритма, а не пытаться его создать?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...