[Flask] Populating child models with parent model Fields in Views

Scott Werner scott.werner.vt at gmail.com
Fri Mar 3 15:46:47 EST 2017


Sorry hit send to early...

Assuming  a One to Many relationship:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", backref="parent") # backref="parent"
not backref=("parent")

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


c = Child()
p = Parent()
p.children.append(c)
session.add(p)
session.commit()

# or

p = Parent() # if new: session.add(p)
c = Child(parent=p)
session.add(c)
session.commit()

http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html

-- 
Scott Werner
scott.werner.vt at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20170303/35b12cfe/attachment.html>


More information about the Flask mailing list