Я пробую Peewee ORM с FLASK.Я создал две модели: Автор и Статья.Автор has_many статей.Таким образом, у таблицы article есть внешний ключ author_id.
Вот мои модели:
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)
У меня есть конечная точка в api колбыгде я публикую идентификатор статьи и идентификатор автора.Я пытаюсь получить статью и автора и связать их:
@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'}
Однако либо Article.select().where(Article.nytimes_id == article_nyId).get()
, либо Author.select().where(Author.id == author_id).get()
всегда поднимают IndexError: tuple index out of range
.Я не понимаю это сообщение об ошибке или что я делаю не так здесь.
Вот полный след:
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