Search code examples
pythonpostgresqlflaskpeewee

Cant perform Error on postgresql database with peewee (Python) : IndexError: tuple index out of range


I am trying out Peewee ORM with FLASK. I created two models : Author and Article. An author has_many articles. Thus table article has a foreign key author_id.

Here are my models :

class BaseModel(Model):
    class Meta:
        database = psql_db
class Article(BaseModel):
    id = PrimaryKeyField(null=False)
    author_id = ForeignKeyField(Author, backref='articles', null=True)
    headline = TextField(null=True)
    snippet = TextField(null=True)
    publication_date = DateTimeField(null=True)
    nytimes_id = CharField(max_length=100, unique=True)



@property
def serialize(self):
    data = {
        'id': self.id,
        'headline': str(self.headline).strip(),
        'snippet': str(self.snippet).strip(),
        'publication_date': str(self.publication_date).strip(),
    }

    return data

def __repr__(self):
    return "{}, {}, {}, {}, {}".format(
        self.id,
        self.headline,
        self.snippet,
        self.publication_date
    )

```

class BaseModel(Model):
    class Meta:
        database = psql_db

class Author(BaseModel):
    id = PrimaryKeyField(null=False)
    full_name = CharField(max_length=100)
    description = TextField(null=True)

I then have an endpoint in my flask api where I post an article id and author id. I try to get the article and the author and associate them :

@app.route('/api/v1/associate-article-author', methods=['POST'])
def associate_author_article():
    author_id = request.json['author_id']
    article_nyId = request.json['selected_article_nyid']
    author = Author.select().where(Author.id == author_id).get()
    article = Article.select().where(Article.nytimes_id == article_nyId).get()
    article.author = author
    article.save()
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

However either Article.select().where(Article.nytimes_id == article_nyId).get() or Author.select().where(Author.id == author_id).get() always raise IndexError: tuple index out of range. I dont understand this error message or what I am doing wrong here.

Here's the complete traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/davidgeismar/code/davidgeismar/react-app/nytimes-api/api.py", line 62, in associate_author_article
    print(article)
  File "/Users/davidgeismar/code/davidgeismar/react-app/nytimes-api/models/article.py", line 39, in __repr__
    self.publication_date
IndexError: tuple index out of range

Solution

  • The problem is in Article.__repr__

    def __repr__(self):
        return "{}, {}, {}, {}, {}".format(
            self.id,
            self.headline,
            self.snippet,
            self.publication_date
        )
    

    The format string contains five placeholders, but only four values are provided, hence the IndexError.