Sebastian Sebastian - 1 month ago 9
Python Question

Is there any difference between these two one-to-many relationships?

class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
cityname = db.Column(db.String(50))
country_id = db.Column(db.Integer, db.ForeignKey('country.id'))
country = db.relationship('Country',
backref=db.backref('cities', lazy='dynamic'))

class Country(db.Model):
id = db.Column(db.Integer, primary_key=True)
countryname = db.Column(db.String(50))


Is there any difference between these two one-to-many relationships?

class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
cityname = db.Column(db.String(50))
country_id = db.Column(db.Integer, db.ForeignKey('country.id'))


class Country(db.Model):
id = db.Column(db.Integer, primary_key=True)
countryname = db.Column(db.String(50))
cities = db.relationship('City', backref='country', lazy='dynamic')


Are these two identical methods for capturing that a Country has many cities?

Answer Source

Yes, the two methods achieve the same effect of one-to-many relationship (the table construct is identical), the difference being where the relationship is declared.

My personal preference is to declare the relationship on both models, as it is more explicit and helps with the IDE (auto-complete). You can do this using back_populates in place of backref.

Takes a string name and has the same meaning as backref, except the complementing property is not created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate back_populates to this relationship to ensure proper functioning.

class City(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...
    country_id = db.Column(db.Integer, db.ForeignKey('country.id'))
    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')