Question

Flask beginner here. I have a little Flask app using the following model:

class Question(db.Model):
    __tablename__ = 'questions'
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String, nullable=False)

class Answer(db.Model):
    __tablename__ = 'answers'
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String, nullable=False)

    question_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
    question = db.relationship("Question", backref="answers")

I fire up the admin using the following lines in my app:

admin = Admin(app)
admin.add_view(ModelView(Question, db.session))
admin.add_view(ModelView(Answer, db.session))

Now in the create form for the answer model, I have a drop down box for question, but it's not populated properly:

Answer create form with Flask-Admin

The quickstart guide doesn't cover models with foreign key relationships and although there are some implementation examples available, they are not documented at all. I'm having a hard time figuring out what is really necessary here and how this works.

Was it helpful?

Solution

Figured it out thanks to a friendly IRC user called mattupstate! The models need to have __str__() implemented:

class Question(db.Model):
    __tablename__ = 'questions'
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String, nullable=False)

    def __str__(self):
        return self.text

OTHER TIPS

For those interested, this solution didn't seem to work for me. What I did to fix it was to override the model view, and explicitely remove the column I didn't want (in this case, the one concerned by the relationship annotation).

You can find my models.py and my overriden model views here: github repo or in this gist

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top