Reputation: 1
If I have two tables with same columns, ex. a table called Toyota and a table called Honda, how can I map these two tables with one model (maybe called Car) in flask?
Upvotes: 0
Views: 972
Reputation: 127180
While you can map multiple tables to a single class, what you are asking for is probably better solved with inheritance. There are two main types of inheritance: joined or single table. Since your example says that the type is the only thing different, all other columns being the same, single table seems more appropriate.
class Car(db.Model):
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String, nullable=False)
wheels = db.Column(db.Integer, nullable=False, default=4)
__mapper_args__ = {
'polymorphic_on': type,
}
class TeslaModelS2014(Car):
__mapper_args__ = {
'polymorphic_identity': 'Tesla Model S 2014',
}
This is a really contrived example; inheritance isn't really appropriate at all here. All cars can be represented without making subclasses. If you have subclasses, you have to make one for each make/model/year in existence, which is ridiculous.
Upvotes: 3
Reputation: 18531
If you have two tables with the same columns, your database schema could probably be done better. I think you should really have a table called CarMake, with entries for Toyota, Honda etc, and another table called Car which has a foreign key to CarMake (e.g. via a field called car_make or similar).
That way, you could represent this in Flask with two models - one for Car and one for CarMake.
Upvotes: 1