warmspringwinds
warmspringwinds

Reputation: 1177

Flask-admin separate view for models filtered by foreign key

I have two sql-alchemy classes. One is Quiz and another one is Reply:

class Quiz(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  quiz_question = db.Column(db.Text)
  quiz_date = db.Column(db.DateTime)
  replies = db.relationship("Reply")

class Reply(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  reply_text = db.Column(db.Text)
  reply_date = db.Column(db.DateTime)
  reply_mark = db.Column(db.Integer)
  user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
  quiz_id = db.Column(db.Integer, db.ForeignKey('quiz.id'))

I was able to create a view for each of those models with CRUD functionality.

I want to know what is the cleanest way to create separate view with CRUD for each group of replies related to one quiz (by quiz id). So that the list of related replies will be available through 127.0.0.1/reply/<quiz_id>.

Thank you.

Edit: I look for something like this but dependent on the quiz id.

Upvotes: 0

Views: 498

Answers (1)

warmspringwinds
warmspringwinds

Reputation: 1177

The easiest way to solve this problem that I found was to add a link for each quiz to a page with replies where the filter for the field quiz_id is applied.

class Replies_view(ModelView):
  named_filter_urls = True
  column_filters = ("quiz_id",)

class Quiz_view(ModelView):
def _question_formatter(view, context, model, name):
    return Markup(
        "<a href='%s'>%s</a>" % (
            flask.url_for('reply.index_view', flt1_quiz_id_equals=model.id),
            model.quiz_question
        )
    ) if model.quiz_question else ""

column_formatters = {
    'quiz_question': _question_formatter
}

Upvotes: 1

Related Questions