0

I'm coding an application connected with a PostgreSQL database and sqlalchemy as the ORM. I have two classes in the simplified schema (camera and room) that I can use but without any relationship. So for example if I select all the room I will not be able to list their cameras.

The error:

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Room->room'. Original exception was: When initializing mapper mapped class Room->room, expression 'Camera' failed to locate a name ('Camera'). If this is a class name, consider adding this relationship() to the <class 'models.room.Room'> class after both dependent classes have been defined.

# room.py
from sqlalchemy import Integer, Column, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class Room(Base):
    __tablename__ = 'room'

    id_room = Column(Integer, primary_key=True)

    cameras = relationship("Camera", back_populates="room")
# camera.py
from sqlalchemy import Integer, Column, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class Camera(Base):
    __tablename__ = 'camera'

    id_camera = Column(Integer, primary_key=True)

    id_room = Column(Integer, ForeignKey('room.id_room'))

    room = relationship("Room", back_populates="cameras")
rfkortekaas
  • 6,049
  • 2
  • 27
  • 34
rafael anno
  • 11
  • 1
  • 4

1 Answers1

0

Just define both the classes in a single models.py file -

# models.py

from sqlalchemy import Integer, Column, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Room(Base):
    __tablename__ = 'room'
    id_room = Column(Integer, primary_key=True)
    cameras = relationship("Camera", back_populates="room")


class Camera(Base):
    __tablename__ = 'camera'
    id_camera = Column(Integer, primary_key=True)
    id_room = Column(Integer, ForeignKey('room.id_room'))
    room = relationship("Room", back_populates="cameras")
Vikas Ojha
  • 6,742
  • 6
  • 22
  • 35