from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) class City(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), index=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) name = db.Column(db.String(32), index=True) cities = db.relationship('City', back_populates='country') # The addition of the line: # capital = db.Column(db.Integer, db.ForeignKey('city.id')) # triggers "sqlalchemy.exc.AmbiguousForeignKeysError". def test(): db.drop_all() db.create_all() france = Country(name='France') db.session.add(france) db.session.commit() # Must commit to get france.id. paris = City(name='Paris', country_id=france.id) limoges = City(name='Limoges', country_id=france.id) db.session.add(paris) db.session.add(limoges) db.session.commit() p = City.query.filter_by(name='Paris').first() assert(p is not None) assert(p.country_id == france.id) l = City.query.filter_by(name='Limoges').first() assert(l is not None) assert(l.country_id == france.id) f = Country.query.filter_by(name='France').first() assert(f is not None) assert(len(f.cities) == 2) test()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question