Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy, relation vs relationship

In some sqlalchemy tutorials, relation function used to define sql-relationships. like this:

class Movie(DeclarativeBase):
    __tablename__ = "movies"

    movie_id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    description = Column(Text, nullable=True)
    genre_id = Column(Integer, ForeignKey('genres.genre_id'))
    genre = relation('Genre', backref='movies')
    release_date = Column(Date, nullable=True)

class Director(DeclarativeBase):
    __tablename__ = "directors"

    director_id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    movies = relation(Movie, secondary=movie_directors_table, backref="directors")

But some articles offering the relationship function, i.e:

class Address(Base):
     __tablename__ = 'addresses'
     id = Column(Integer, primary_key=True)
     email_address = Column(String, nullable=False)
     user_id = Column(Integer, ForeignKey('users.id'))
     user = relationship("User", backref=backref('addresses', order_by=id))

My question is: what is the differences between those two functions, and at least a reason to use each one.

Thanks is advance

like image 544
pylover Avatar asked Sep 02 '13 17:09

pylover


People also ask

What is a relationship in SQLAlchemy?

The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship.

Is there something better than SQLAlchemy?

Django, Pandas, Entity Framework, peewee, and MySQL are the most popular alternatives and competitors to SQLAlchemy.

What is many to many relationship in SQLAlchemy?

Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.


1 Answers

According to docs, they are synonyms:

sqlalchemy.orm.relation(*arg, **kw)

A synonym for relationship().

And, actually:

Changed in version 0.6: relationship() was renamed from its previous name relation().

So, better use relationship() as it is the most "fresh" name of the two.

like image 120
alecxe Avatar answered Oct 04 '22 12:10

alecxe