R
R
REDkiy2015-03-01 10:54:00
Flask
REDkiy, 2015-03-01 10:54:00

How to use relationships in sqlalchemy?

I'm learning flask and sqlalchemy.
I took an example from the documentation:

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

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

I don’t fully understand the meaning of the design:
children = relationship("Child", backref="parent")
What are its tasks? How to use in queries?
How much is it needed if ForeignKey('parent.id') is specified?
It is difficult for me to navigate the sqlalchemy documentation, I will be glad to see links to examples of using relations.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2015-03-01
@nextel

This is the implementation of a 1-to-many relationship, 1 parent, a bunch of children, according to the last line, you can remove all the children that refer to this parent from the database

R
REDkiy, 2015-03-10
@REDkiy

In general, I understood. I don't know how right I am. My vision is this.
Relationships are more of an object approach. When using a relation, a "like a field" is added to the table, in which there is an iterable object (like a list) of values ​​from the second table corresponding to the primary key from the first table.
join is more like an SQL statement, it joins two tables by the primary key of the first table and its value from the second. And we work with the resulting table. In this case, you can do without relationships completely.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question