自定义uint64字段用作主键时的外键查询错误

时间:2015-12-14 00:25:16

标签: python sql python-3.x peewee

我需要uint64字段作为我的数据库的主键字段,预计其他模型使用外键指向此模型。结果代码是这样的:

from peewee import *

db = SqliteDatabase('test.db')

class UInt64(Field):
    db_field = 'bigint'

    def db_value(self, value):
        return value - (1<<63)

    def python_value(self, value):
        return value + (1<<63)

class Foo(Model):
    id = UInt64(primary_key = True)

    class Meta:
        database = db

class Bar(Model):
    id = UInt64(primary_key = True)
    foo = ForeignKeyField(Foo, related_name='bars')

此代码适用于我所使用的所有请求:

>>> f = Foo.create(id=10000)
>>> Bar.create(id=123, foo=f)
<ptest.Bar object at 0x7f2fde7f7e10>
>>> b = Bar.get()
>>> b.id
123
>>> b.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 1151, in __get__
    return self.get_object_or_id(instance)
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 1142, in get_object_or_id
    obj = self.rel_model.get(self.field.to_field == rel_id)
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 4403, in get
    return sq.get()
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 2812, in get
    return clone.execute().next()
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 2859, in execute
    self._qr = ResultWrapper(model_class, self._execute(), query_meta)
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 2555, in _execute
    return self.database.execute_sql(sql, params, self.require_commit)
  File "/usr/local/lib/python3.4/dist-packages/peewee.py", line 3359, in execute_sql
    cursor.execute(sql, params or ())
OverflowError: Python int too large to convert to SQLite INTEGER

似乎python值和db值之间的某处转换未正确完成。对我来说看起来像个错误。

如果没有直接在Bar中将foo id保存为UInt64而不是使用ForeignKeyField,那么如何修复它?

2 个答案:

答案 0 :(得分:0)

这看起来像你正在使用的Python sqlite驱动程序中的一个错误。它试图转换为int并溢出。

答案 1 :(得分:0)

这是peewee中的一个错误,现在已修复: https://github.com/coleifer/peewee/issues/791