2016-05-18 87 views
3

我有以下代碼查詢我的peewee數據庫。我在具有term.sets_term_id的行上的for循環中出現錯誤。這是錯誤TermsDoesNotExist:實例匹配查詢不存在:如果我做了vars(term),那麼sets_terms_id是一個選項。爲什麼我得到這個錯誤,我該如何解決?peewee實例匹配查詢不存在

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

回答

0

的問題是在你的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'})