简体   繁体   English

将外键设置为nullable = false?

[英]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? 如果始终期望数据库中该列的外键,您是否将外键设置为nullable=false

I'm using sqlalchemy and have set my models with required foreign keys. 我正在使用sqlalchemy并使用所需的外键设置我的模型。 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. 这有时会导致我更频繁地运行session.commit() ,因为我需要父模型具有id并完全创建以便在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')

You don't need to do session.commit() to get an ID; 您不需要使用session.commit()来获取ID; session.flush() will do. session.flush()会做的。

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 INSERT s in. You can simply do: 更好的是,如果设置关系,则根本不需要获取ID,因为SQLalchemy将确定执行INSERT的顺序。您可以简单地执行:

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

and it will work fine. 它会工作正常。

I would suggest that you'd better not set nullable=False. 我建议你最好不要设置nullable = False。 Make foreign key nullable is very reasonable in many situations. 在很多情况下使外键可空可以很合理。 In your scenario, for example, if I want to insert a hotel whose location is currently underdetermined, you can not accomplish this with the foreign key not null. 例如,在您的方案中,如果我要插入当前位置不确定的酒店,则无法使用外键非空来完成此操作。 So the best practice when using foreign key is to set it nullable. 因此,使用外键时的最佳做法是将其设置为可空。

See necessary nullable foreign key Any example of a necessary nullable foreign key? 查看必要的可空外键任何必需的可空外键的示例?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM