Skip to content

SQLAlchemy relationship attribute with collection_class option #113

@dabajabaza

Description

@dabajabaza

The bug
I have sqlalchemy model with relationship attribute states and collection_class option.
I define colanderalchemy schema that NOT includes attribute states, so I expect that this attribute would be ignored even if it's exists in input data.
Colanderalchemy generates error while trying to objectify input data with states in it.

Expected behavior
Schema objectified successfully without errors. The states attribute is ignored.

To Reproduce

I used the following code:

from sqlalchemy.orm import relationship
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
    BigInteger,
    Column,
    ForeignKey,
    Unicode,
)
from colanderalchemy import SQLAlchemySchemaNode

Base = declarative_base()

class State(Base):
    __tablename__ = "State"
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    code = Column(Unicode(50), nullable=False, unique=True)
    name = Column(Unicode(50), nullable=False)


class Module(Base):
    __tablename__ = "Module"
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    name = Column(Unicode(50), nullable=False)
    state_id = Column(ForeignKey(State.id))
    states = relationship(State,
                          uselist=True,
                          collection_class=attribute_mapped_collection("code"),
                          )


schema = SQLAlchemySchemaNode(
    Module,
    includes=[
        "name",
    ],
    title="Module schema",
)
schema.objectify({"name": "Some Name", "states": {}})
Traceback (most recent call last):
  File "src/script.py", line 44, in <module>
    schema.objectify({"name": "Some Name", "states": {}})
  File "env\lib\site-packages\colanderalchemy\schema.py", line 706, in objectify
    setattr(context, attr, value)
  File "env\lib\site-packages\sqlalchemy\orm\attributes.py", line 459, in __set__
    self.impl.set(
  File "env\lib\site-packages\sqlalchemy\orm\attributes.py", line 1548, in set
    raise TypeError(
TypeError: Incompatible collection type: list is not dict-like

Versions

  • OS: Windows 10
  • Python: 3.8.10
  • SQLAlchemy: 1.4.26
  • colander: 1.8.3
  • ColanderAlchemy: 0.3.4
  • Database: Microsoft SQL Server 2019

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions