peewee实例匹配查询不存在

时间:2016-05-18 19:59:07

标签: python flask peewee

我有以下代码,我在查询我的peewee数据库。我在具有term.sets_term_id的行上的for循环中收到错误。这是错误TermsDoesNotExist:实例匹配查询不存在:如果我执行变量(term),则sets_terms_id是一个选项。为什么我会收到该错误以及如何解决?

def get_api_response(id):
    response = {}
    print("id is " + str(id))
    try:
        sets = models.Sets.select().where(models.Sets.user_id == id)

    except models.DoesNotExist:
        return json.loads({'error' : 'that set does not exist'})
    else:
        print("it was successful")
        for term in sets:
            print(term.sets_term_id)

以下是我的套装和条款

class Terms(UserMixin, BaseModel):
    term_id = CharField()
    sets_id = CharField()
    rank = IntegerField()
    term = TextField()
    definition = TextField()

    @classmethod
    def include_term(cls, set_id, term_id, definition, rank, term, **kwards):
        try:
            cls.select().where(cls.term_id == term_id).get()
        except cls.DoesNotExist:
            print("putting term into db")
            concept = cls(
                sets_id = set_id,
                term_id = term_id,
                definition = definition,
                rank = rank,
                term= term)
            concept.save()
            print(concept.term)
            print("term saved to db")
            return concept
        else:
            raise Exception("Term with that id already exists")

class Sets(UserMixin, BaseModel):
    user_id = CharField()
    name_set = CharField()
    #created_date = DateField()
    #modified_date = DateField()
    #published_date = DateField()
    sets_term_id = ForeignKeyField(Terms, to_field="sets_id")

    @classmethod
    def include_set(cls, user_id, name_set, sets_term_id, **kwards):
        try:
            cls.select().where(
                (cls.name_set == name_set) | (cls.sets_term_id == sets_term_id)
            ).get()
        except cls.DoesNotExist:
            print("putting set into db")
            quizlet_set = cls(
                user_id = user_id, 
                name_set = name_set,
                sets_term_id = sets_term_id)
            print(quizlet_set.name_set)
            quizlet_set.save()
            print("set saved in db")

            return quizlet_set
        else:
            raise Exception("Set with that name already exists")  

1 个答案:

答案 0 :(得分:1)

问题出在你的except块中。

 except models.DoesNotExist:
    return json.loads({'error' : 'that set does not exist'})

应该是:

 except models.Sets.DoesNotExist:
    return json.loads({'error' : 'that set does not exist'})