Error occur when I try to enter data in a relational database createtd with sqlalchemy relationship

Viewed 18

I am a beginner and try to build a relational Database with python sqlalchemy. Here is my code:

class Overall_Account(db.Model):
    __tablename__ = "account"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), unique=True, nullable=False)
    account_img = db.Column(db.String(250), nullable=False)
    branch = db.Column(db.String(250), nullable=False)
    description = db.Column(db.Text, nullable=False)
    fops = relationship("Field_OF_Play", back_populates="large_account")

class Field_Of_Play(db.Model):
    __tablename__ = "fop"
    id = db.Column(db.Integer, primary_key=True)
    account_id = db.Column(db.Integer, db.ForeignKey("account.id"))
    large_account = relationship("Overall_Account", back_populates="fops")

    fop_name = db.Column(db.String(250), unique=True, nullable=False)
    fop_description = db.Column(db.Text, nullable=False)
    fop_business = db.Column(db.Text, nullable=False)
    value_add = db.Column(db.Text, nullable=False)
    customer_perception = db.Column(db.Text, nullable=False)

db.create_all()

new_account = Overall_Account(
    id=1,
    name='Account Name',
    account_img='https://picture.img',
    branch='retail',
    description='some text'
)

db.session.add(new_account)
db.session.commit()

The database is created but if I try to enter data, I get following error message:

sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Overall_Account->account, expression 'Field_OF_Play' failed to locate a name ('Field_OF_Play'). If this is a class name, consider adding this relationship() to the <class 'main.Overall_Account'> class after both dependent classes have been defined.

I can not find the error. Can anybody help?

1 Answers

remove fops from Overall_Account and add change the relationship in Field_Of_Play as:

large_account = relationship("Overall_Account", backref="fops"
Related