How to enter value for foriegn key field via sqlalchemy

7 views
Skip to first unread message

sudheesh ks

unread,
Jun 22, 2015, 3:44:49 PM6/22/15
to sqlal...@googlegroups.com
I have models:

{
class
Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(2000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) comments = db.relationship('Comment', backref='parent_post', lazy='dynamic') class Comment(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
}

When entering a post to database I do this:

{
if form.validate_on_submit(): post = Post(body=form.post.data, author=g.user) db.session.add(post) db.session.commit()
} This is working right.

But how can I enter a comment to database if I want to pass the 'post.id' value directly
instead of object 'post'. (Not able to 'pass' object via form in html)

{
if form.validate_on_submit(): comment = Comment(body=form.post.data, parent_post=form.p_id.data) db.session.add(post) db.session.commit()
}

currenntly p_id holds value post.id and it gives me error:

AttributeError: 'int' object has no attribute '_sa_instance_state'
Please help

Simon King

unread,
Jun 22, 2015, 3:50:46 PM6/22/15
to sqlal...@googlegroups.com
The columns that you set up on your Comment class (including the
post_id foreign key column) can be used directly.

ie.

Comment(body=form.post.data, post_id=form.p_id.data)

Hope that helps,

Simon

sudheesh ks

unread,
Jun 22, 2015, 4:29:45 PM6/22/15
to sqlal...@googlegroups.com
So thanks... It worked. I made that mistake in code and had been trying to solve that for 2 days.


--
You received this message because you are subscribed to a topic in the Google Groups "sqlalchemy" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sqlalchemy/8QpC_kh6Yds/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages