编程语言
首页 > 编程语言> > python – peewee实例匹配查询不存在

python – 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")  

解决方法:

问题出在你的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'})

标签:python,flask,peewee
来源: https://codeday.me/bug/20190706/1395379.html