esac
esac

Reputation: 24685

How to reference the child of a many to one relationship in SQLAlchemy?

Using the example off the documentation, I have the following code. When I try to append I get the error:

AttributeError: 'NoneType' object has no attribute 'append'    

Obviously even without using append the parent.child is of NoneType. I don't know how to work with this relationship.

Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref="parents")


class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine("mysql://localhost/test", echo=False)
Session = sessionmaker(bind=engine)
session = Session()

metadata = Base.metadata
metadata.drop_all(engine)
metadata.create_all(engine)

parent = Parent()
child = Child()
parent.child.append(child)

Upvotes: 0

Views: 1059

Answers (1)

Will
Will

Reputation: 4528

You set up the many to one relationship so that a parent can have one child and a child can have many parents. If that's how you intended, you can just set the child like so:

parent.child = child

A child, however, could add a parent like so:

child.parents.append(parent)

If this isn't how you intended, you will have to switch the relationship so that parents can have multiple children by setting up a Many to Many relationship or by switching the direction of the many to one.

Upvotes: 2

Related Questions