Casey Casey - 2 months ago 16
Python Question

Set foreign key to nullable=false?

Do you set your foreign keys as nullable=false if always expect a foreign key on that column in the database?

I'm using sqlalchemy and have set my models with required foreign keys. This sometimes causes me to run session.commit() more often, since I need the parent model to have an id and be fully created in order to build a child object in the ORM. What is considered best practice? My models are below:

class Location(Base):
__tablename__ = 'locations'

id = Column(Integer, primary_key=True)
city = Column(String(50), nullable=False, unique=True)

hotels = relationship('Hotel', back_populates='location')


class Hotel(Base):
__tablename__ = 'hotels'

id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False, unique=True)
phone_number = Column(String(20))
parking_fee = Column(String(10))
location_id = Column(Integer, ForeignKey('locations.id'), nullable=False)

location = relationship('Location', back_populates='hotels')

Answer

You don't need to do session.commit() to get an ID; session.flush() will do.

Even better, you don't need to get an ID at all if you set the relationship because SQLalchemy will figure out the order to do the INSERTs in. You can simply do:

loc = Location(city="NYC", hotels=[Hotel(name="Hilton")])
session.add(loc)
session.commit()

and it will work fine.

Comments