Set foreign key to nullable=false?
<p>Do you set your foreign keys as nullable=false if always expect a foreign key on that column in the database? </p>

<p>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:</p>

<pre><code>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')
</code></pre>

<p>You don't need to do <code>session.commit()</code> to get an ID; <code>session.flush()</code> will do.</p>

<p>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 <code>INSERT</code>s in. You can simply do:</p>

<pre><code>loc = Location(city="NYC", hotels=[Hotel(name="Hilton")])
session.add(loc)
session.commit()
</code></pre>

<p>and it will work fine.</p>

python sqlalchemy