1

具有以下功能 views.py

def ask_question():
        form = QuestionForm()
        if form.validate_on_submit():
            question = Question(title=form.title.data, text=form.text.data)
            db.session.add(question)
            db.session.commit()
            return redirect('/questions/%d/' % question.id)
        return render_template('ask_question.html', form=form)

如何获得创建模型的 id 以将其置于断言中?

def test_can_post_question(self):
    response = self.tester.get('/new-question')
    self.assert_200(response)
    form = self.get_context_variable('form')
    self.assertIsInstance(form, QuestionForm)
    response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?',
                                                       'text': 'What is it?'})
    self.assertRedirects(response, '/questions/%d' % created_question.id)
                                                     #^ how can I get id of created model here?

我正在使用 Flask、Flask-SQLAlchemy、Flask-Testing

4

1 回答 1

1

查询创建的问题对象。作为副作用,您可以测试问题是否已创建。

...
q = Question.query.filter_by(title='What about somestuff in Flask?').first()
self.assertRedirects(response, '/questions/%d/' % q.id)
于 2015-01-17T09:29:08.177 回答