How to pass array of SQLAlchemy model to another table

Viewed 67

I am very new to Flask-SQLAlchemy and I am facing an issue where I have Reader and Doorgroup tables and I want to create Doorgroup entry passing an array of Reader objects to one of its columns.

from .base_model import BaseModel
from app.globals import db
from typing import Dict, List


class Doorgroup(BaseModel):
    __tablename__ = 'doorgroups'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    reader_id = db.Column(db.Integer, db.ForeignKey('readers.id'))
    doors = db.relationship('Reader', lazy='joined', foreign_keys=reader_id, backref='reader_doorgroups')
    cardgroup = db.relationship('Cardgroup', lazy='joined', foreign_keys=cardgroup_id)



class Reader(BaseModel):
    __tablename__ = 'readers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, unique=True)
    doorgroup_id = db.Column(db.Integer, db.ForeignKey('doorgroups.id', use_alter=True))
    doorgroups = db.relationship('Doorgroup', lazy='joined', backref='readers', post_update=True, foreign_keys=doorgroup_id)


doors = [16, 73, 345, 34, 363]
for door in doors:
   reader = Reader.find(id=door)
   readers.append(reader)

doorgroup = Doorgroup(name=name,cardgroup=cardgroup, doors=readers)

However when I do that, it throws an error:

AttributeError: 'list' object has no attribute '_sa_instance_state'

Is it not possible to do that or is there a workaround for this issue?

0 Answers
Related