Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SqlAlchemy Adjacency List Relationship backfref unexpected error

I am working on a small project where I am using Flask-SqlAlchemy to implement an adjacency list relationship. I have a model (table) which has an attribute for db.Relationship() which references the parent_id column of the same table.

Here is the following code (partial):

class Node(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(80))
    folder_id = db.Column(db.Integer, db.ForeignKey('node.id'))

    children = db.relationship('Node', backref = 'parent', remote_side=[id])

When I try to add a child folder to a parent folder using the backref attribute on the child in the Python Shell such as the following code(partial) :

parentNode = Node('title1')
db.session.add(parent)
db.session.commit()

childNode = Node('title2')
child.parent = parentNode

However, I get the following erros after I try that in the Python shell:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

TypeError: Incompatible collection type: Node is not list-like

I have read the SqlAlchemy docs to figure out a solution and they have similar syntax for adjacency list relationships. It has a similar example but does not show how one can add a parent node to a child node like I was trying in the shell. The reason for adding the parent node into the child's backref property is that it works with one-to-many relationships. Any help in finding the problem with the code would be greatly appreciated... Please feel free to suggest alternate solutions.

Thanks!

like image 763
shafayet Avatar asked Feb 26 '13 05:02

shafayet


1 Answers

You configure the relationship in a wrong way. Please do this one:

from sqlalchemy.orm import backref
class Node(db.Model):
    # ...
    children = db.relationship('Node', backref=backref('parent', remote_side=[id]))

or

class Node(db.Model):
    # ...
    parent = db.relationship("Node", backref='children', remote_side=[id])
like image 149
van Avatar answered Nov 02 '22 14:11

van