Sebastian Sebastian - 1 month ago 8
Python Question

Country-to-City + Country-to-Capital = One-To-Many + One-To-One?

How would you augment this one-to-many relationship, making one on the 'many' side a distinguished one.

Using a concrete example, how would the notion of a capital be introduced in the following model? Would it be an additional one-to-one mapping? Would it interfere with the existing one-to-many? Would merely introducing a db.Boolean

be sufficient? Would this last be idiomatic or is there a more fitting solution?

class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
country_id = db.Column(db.Integer, db.ForeignKey(''))
country = db.relationship('Country', back_populates='cities')

class Country(db.Model):
id = db.Column(db.Integer, primary_key=True)
cities = db.relationship('City', back_populates='country')

Answer Source

You can either make a new Capital table, which contains one row per Country containing the Country ID and City ID, or you could just add a column to the Country table containing the Capital City ID. Either of these will provide more efficient lookup and more compact storage than a boolean is_capital for each City.