Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Admin ModelView isn't handling foreign keys right (blank drop down)

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.

like image 853
Alexander Rechsteiner Avatar asked Jan 13 '23 03:01

Alexander Rechsteiner


1 Answers

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
like image 167
Alexander Rechsteiner Avatar answered May 16 '23 07:05

Alexander Rechsteiner