E
E
EnotShow2021-11-09 02:34:45
Python
EnotShow, 2021-11-09 02:34:45

Why "Column expression expected for argument"?

I write applications using SQLALCHEMY, but I get an error during application startup

sqlalchemy.exc.ArgumentError: Column expression expected for argument 'foreign_keys'; got 'post.id'.


I would be very grateful for help in solving the problem

Full version of the code:
from flask import Flask, request, flash
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.testing import db
from wtforms_alchemy import ModelForm

app = Flask(__name__)
app.config.update(
    DEBUG=True,
    Secret_key='This must been secret !',

    SQLACHEMY_DATABESE_URI='sqlite:///app_db.db',
    SQLALCHEMY_TRACK_NOTIFICATION=False,

    WTF_CSRF_ENABLE=False,
)

db = SQLAlchemy(app)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, index=True)
    post_name = db.Column(db.String(75), nullable=False)
    post_body = db.Column(db.String(3000), nullable=False)

    def __str__(self):
        return '<Post> {}'.format(self.data)


class Comments(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, index=True)

    post_id = db.Column(
        db.Integer,
        db.ForeignKey('post.id'),
        index=True,
        nullable=False,
    )

    post = db.relationship(Post, foreign_keys=['post_id', ])

    post_comment = db.Column(db.String(1500), nullable=False)

    def __str__(self):
        return '<Comments> {}'.format(self.data)


# Error here !
class PostForm(ModelForm):
    class Meta:
        model = Post()


@app.route('/')
def index():
    return 'Hello from Flask'


@app.route('/add_post', methods=['POST'])
def add_post():
    form = PostForm(request.form)
    if form.validate():
        post_data = Post(**form.data)
        db.session.add(post_data)
        db.session.commit()


if __name__ == '__main__':
    db.create_all()

    app.run()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ramis, 2021-11-09
@EnotShow

Fix it

post = db.relationship('Post', foreign_keys=[post_id, ])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question