0

I've spent hours and still cannot figure it out. I'm receiving Object '<Person at 0x7f284eb4cf90>' is already attached to session '2' (this is '1')

My models:

class Base(ORM):
    id: Optional[int] = Field(primary_key=True)
    created: datetime = Field(default_factory=datetime.utcnow, nullable=False)

class Project(Base, table=True):
    __table_args__ = {'extend_existing': True}
    project_name: str
    start_date: datetime
    end_date: datetime
    owner: str
    cost_center: str
    people: List["Person"] = Relationship(back_populates="project")


class Person(Base, table=True):
    __table_args__ = {'extend_existing': True}
    first_name: str
    last_name: str
    current_project_id: int = Field(foreign_key="project.id")
    project: Optional[Project] = Relationship(back_populates="people")

My Factories:

class BaseFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        sqlalchemy_session = TestSessionLocal()
        sqlalchemy_session_persistence = "commit"

class PersonFactory(BaseFactory):
    class Meta:
        model = models.Person
    
    first_name = factory.Sequence(lambda x: fake.first_name())
    last_name = factory.Sequence(lambda x: fake.last_name())
    current_project_id = factory.SubFactory("tests.factories.ProjectFactory", people=None)
    project = factory.SubFactory("tests.factories.ProjectFactory", people=None)


class ProjectFactory(BaseFactory):
    class Meta:
        model = models.Project

    project_name = factory.Sequence(lambda x: fake.word())
    start_date = factory.Sequence(lambda x: fake.date_time_this_year())
    end_date = factory.Sequence(lambda x: fake.date_time_this_year())
    owner = factory.Sequence(lambda x: fake.name())
    cost_center = factory.Sequence(lambda x: fake.word())
    people = factory.RelatedFactory(PersonFactory, factory_related_name="project")

I have no idea why it says anything about another session. I run tests on docker container and whenever I try to create person's factory object I get the above. Is it related to relationships?

p = person_factory.create()

Appreciate any help

kutasek69
  • 13
  • 3
  • Please always include all relevant imports. Otherwise your code is not complete/reproducible. For example, what is `ORM` in your Models module? What is `factory` in your Factories module? Also, show _reproducible_ code leading to the error and the _full_ error traceback. Lastly: I am sure _most_ of the code you showed is irrelevant to the problem, so you may want to reduce your example and keep only the minimum amount of code necessary to reproduce the problem (only relevant model fields). See here: https://stackoverflow.com/help/mcve – Daniil Fajnberg Mar 23 '23 at 09:30

0 Answers0