'Sqlmodel orm object no attribute xxx error for a relationship attribute ONLY IN AWS LAMBDA FUNCTION

The following is my definition of a sqlmodel orm class and its related orm classes:

class CoursePostgresORM(CourseWithMetadataBase, table=True):
    __tablename__ = '...'
    __table_args__ = {'schema': '...', }
    id_: str = Field(alias='id', sa_column=Column('id', primary_key=True))
    ....

    skills: List['CourseSkillLink'] = Relationship(back_populates='course')
    regions: List['CourseRegionLinkPostgresORM'] = Relationship(back_populates='course')

    class Config:
        allow_population_by_field_name = True
    def to_elasticsearch_doc(self):
        skills = [skill for skill in self.skills]
        doc = {
            ...
        }
        return doc

class CourseSkillLink(SQLModel, table=True):
    __tablename__ = '...'
    __table_args__ = {'schema': '...', }
    id_: int = Field(alias='id', sa_column=Column('id', primary_key=True))
    course_id: str = Field(foreign_key='course_catalog.courses.id')
    skill_id: int = Field(foreign_key='public.skills.id')
    created_at: datetime
    updated_at: datetime

    course: 'CoursePostgresORM' = Relationship(back_populates='skills')
    skill: 'SkillPostgresOrm' = Relationship(back_populates='courses')

class SkillPostgresOrm(SQLModel, table=True):
    __tablename__ = 'skills'
    __table_args__ = {'schema': 'public'}
    id_: int = Field(alias='id', sa_column=Column('id', primary_key=True))
    skill_level: int
    parent_id: Optional[int]
    deactivated_at: Optional[datetime]
    created_at: Optional[datetime]
    updated_at: Optional[datetime]
    last_updated_by: Optional[str]
    name: str
    is_selected_skill: bool

    courses: List['CourseSkillLink'] = Relationship(back_populates='skill')

When run the following code on my local, everything went fine.

with Session(POSTGRES) as session:
    res = session.exec(course_stm)

However, I was thrown with the following error while running this in one of the aws lambda functions.

  "errorMessage": "'CoursePostgresORM' object has no attribute 'skills'",
  "errorType": "AttributeError",
  "stackTrace": [
    "  File \"/var/task/index_to_es.py\", line 21, in lambda_handler\n    courses = fetch_courses_from_sql()\n",
    "  File \"/var/task/index_to_es.py\", line 38, in fetch_courses_from_sql\n    es_docs = [row.to_elasticsearch_doc() for row in res.all()]\n",
    "  File \"/var/task/index_to_es.py\", line 38, in <listcomp>\n    es_docs = [row.to_elasticsearch_doc() for row in res.all()]\n",
    "  File \"/opt/python/appliedx_data_object/course.py\", line 196, in to_elasticsearch_doc\n    skills = [skill for skill in self.skills]\n"

I've spent the whole day trying to figure this out but had no luck. Any input is welcome. Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source