无法正确检查实例的模型类型

时间:2016-10-27 16:34:35

标签: python django

无法弄清楚,为什么“if statement”会返回不正确的值

    next_step_type = type(next_step)()  # this returns 'Quiz' which is correct

    # if statement returns step_type_letter = 't' which is not correct
    if next_step_type is "Quiz":
        step_type_letter = 'q'
    else:
        step_type_letter = 't'

2 个答案:

答案 0 :(得分:0)

也许尝试这样:

next_step_type = type(next_step)
if next_step_type is Quiz:
    step_type_letter = 'q'
else:
    step_type_letter = 't' 

编辑: 或者如果你使用isinstance():

if isinstance(next_step_type(), Quiz):
    step_type_letter = 'q'
else:
    step_type_letter = 't'

答案 1 :(得分:0)

这也应该有用,可能更容易阅读?

from .models import Quiz

# next_step is a model object, e.g. next_step = Quiz.objects.create(...)
if isinstance(next_step, Quiz):
    ...
else:
    ...