Itchy
Itchy

Reputation: 2414

Create link to related tables in SQLAlchemy Declarative

I'm using Flask with SQLAlchemy and Declarative, but am new to it. And I have a Parent- and a Child-Tabele/Class.

In my database there are thousands of parents. And so far everything is working, but the two tables do not link nicely for the user.

I'd like to provide a link in the parent to create (and eventually also update) a child, without the user having to find the parents id again in the very long list.

I've studied the documentation of Declarative already, but found no hint how to bring this to work.

My code so far is:

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

and:

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

Upvotes: 1

Views: 487

Answers (1)

Remo L.
Remo L.

Reputation: 760

When I understand your question correctly you can do the following:

Define a field in your Child Class:

criterias = relationship('Criteria', secondary=criteria_controls, backref=backref('criteria', lazy='dynamic'))

See the Backref documentation for more help

Let me know if this helps. Maybe you can provide an example parent-child relation of yours?

cheers

Edit:

I see now that I didn't fully get to you with my answer. Maybe it is simpler than you think. I am still not quite sure what you want to acomplish, but you can create a new child simply by doing this:

p = Parent()
p.child = Child()
db.add(p)
db.commit()

you should be able to directly access the child object by the child field.

to verify try this:

print(type(p.child))

hope this helps.

Upvotes: 1

Related Questions