Peewee ORM给出了IntegrityError:user_id可能不是NULL

时间:2013-12-19 14:12:03

标签: python sqlite orm flask peewee

我正在尝试将Peewee ORM用于我的新(Flask)网站,现在我遇到了一个问题。我刚刚创建了一个简单的模型:

from peewee import TextField, DateTimeField, IntegerField, ForeignKeyField
from app import db

ROLE_USER = 0
ROLE_ADMIN = 1

class User(db.Model):
    nickname = TextField()
    email = TextField()
    role = IntegerField(default = ROLE_USER)

class Post(db.Model):
    body = TextField()
    timestamp = DateTimeField()
    user = ForeignKeyField(User, related_name='posts')

所以我创建了两个用户,之后我想创建一个新帖子。我是这样做的:

>>> from app.models import User
>>> u = User(nickname='john', email='john@email.com', role=0)
>>> u.save()
>>> from app.models import Post
>>> from datetime import datetime as dt
>>> p = Post(body='FIPO!!', timestamp = dt.now(), author=u)
>>> p.save()
No handlers could be found for logger "peewee"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 2479, in save
    ret_pk = self.insert(**field_dict).execute()
  File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1775, in execute
    return self.database.last_insert_id(self._execute(), self.model_class)
  File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1470, in _execute
    return self.database.execute_sql(sql, params, self.require_commit)
  File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1885, in execute_sql
    return self.sql_error_handler(exc, sql, params, require_commit)
  File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1871, in sql_error_handler
    raise exception
sqlite3.IntegrityError: post.user_id may not be NULL

我不明白user_id显然是NULL,因为据我所知,peewee应该照顾好这个吗?

我做错了什么(如果是的话,那是什么?),或者这是peewee的问题?欢迎所有提示!

1 个答案:

答案 0 :(得分:3)

问题是,当您使用author=时,您正在使用user=

原始

p = Post(body='FIPO!!', timestamp = dt.now(), author=u)

固定

p = Post(body='FIPO!!', timestamp = dt.now(), user=u)