Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of relationship and ForeignKey modules in SQLAlchemy

I'm a little confused over the use of the two modules from SQLAlchemy. This is the code I have:

Base = declarative_base()

class Restaurant(Base):
    __tablename__ = 'restaurant'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class MenuItem(Base):
    __tablename__ = 'menu_item'
    name =Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

I understand that ForeignKey is used to define the foreign key relationship between the restaurant_id column of menu_item table and the id column of restaurant table. But why then is restaurant = relationship(Restaurant) used?

like image 779
Sidharth Samant Avatar asked Jan 23 '16 01:01

Sidharth Samant


People also ask

What does relationship do 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.

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.

How do you create a relationship in a SQLAlchemy flask?

You then create a Flask application instance called app , which you use to configure two Flask-SQLAlchemy configuration keys: SQLALCHEMY_DATABASE_URI : The database URI to specify the database you want to establish a connection with. In this case, the URI follows the format sqlite:/// path/to/database. db .


1 Answers

restaurant_id will refer to an id (the column value). restaurant will refer to a Restaurant instance that will be lazy loaded from the db on access (or eager loaded if you set up the right stuff earlier). If you set backref on the relationship you can also access a list of MenuItem objects from a Restaurant.

like image 144
Jason S Avatar answered Sep 27 '22 15:09

Jason S