Kermit
Kermit

Reputation: 5982

Flask SQLAlchemy custom field name for foreign key?

Relationship = Many Heros have one Planet.

I'd like to be able to call hero.home_planet because the Star Wars characters move around in space a lot. But under my model, the field is called planet_id.

Is there a way to set a custom name for a foreign key field?

Like a planet_id = db.Column( name ='home_planet')?

Could I just change the name of the table name to __tablename__ = 'home_planet'?

class Hero(db.Model):
    __tablename__ = 'heroes'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    race = db.Column(db.String())
    planet_id = db.Column(db.Integer, db.ForeignKey('planets.id'), nullable=True)

    def __repr__(self):
        return '<Hero %r>' % self.name

Upvotes: 0

Views: 755

Answers (2)

Gabe
Gabe

Reputation: 995

With flask_sqlalchemy:

class Planet(db.Model)
    __tablename__ = 'planet'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    heros = db.relationship('Hero', backref='home_planet')

class Hero(db.Model):
    __tablename__ = 'heroes'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    race = db.Column(db.String())
    planet_id = db.Column(db.Integer, db.ForeignKey('planets.id'), nullable=True)

    def __repr__(self):
        return '<Hero %r>' % self.name

Now you can call your_hero.home_planet

Upvotes: 1

djnz
djnz

Reputation: 2050

It's worth going through the SQLAlchemy docs to learn about the huge number of options you can use here, but it sounds like a simple relationship() will work:

planet = relationship('Planet', backref='heroes')

You can now call my_hero.planet, or the reverse my_planet.heroes

Upvotes: 0

Related Questions