2017-08-14 19 views
0

Pony ORM似乎是按Json值的字符串排序的,而不是整數值。有沒有辦法讓這個訂單正確?Pony ORM order_by json積分值

下面是一個例子:

from pony.orm import (
    Database, Required, Optional, db_session, commit, 
    show, Json) 

db = Database() 
db.bind('sqlite', filename=':memory:', create_db=True) 

class Person(db.Entity): 
    name = Required(str) 
    body = Optional(Json, default={}) 

db.generate_mapping(create_tables=True) 


with db_session: 
    Person(name='bort', body={'age': 1}) 
    Person(name='baz', body={'age': 2}) 
    Person(name='bar', body={'age': 10}) 
    Person(name='foo', body={'age': 20}) 

    commit() 

    people = Person.select().order_by(lambda p: p.body['age']) 
    show(people) 

輸出:

id|name|body  
--+----+----------- 
1 |bort|{'age': 1} 
3 |bar |{'age': 10} 
2 |baz |{'age': 2} 
4 |foo |{'age': 20} 

有沒有辦法來解決這個問題,並小馬ORM不支持這一點,還是我做錯了什麼?

+0

試試'lambda p:int(p.body ['age'])''。 – stovfl

+0

你試過這個嗎?我很確定我早些時候嘗試過,並得到一個錯誤消息 - 雖然現在不在計算機上檢查 – freebie

回答

0

Comment: causes Pony to raise and exception:
"TypeError: Function 'int' cannot be used this way: int(p.body['age'])"

無法與pony驗證,嘗試,如果pony接受這一點:

def _int(v): 
    return int(v) 

people = Person.select().order_by(lambda p: _int(p.body['age'])) 

Question: Is there a way to work around this, does Pony ORM not support this

您使用sqlite,是有關文獻jsonstr
變通方法:

lambda p: int(p.body['age']) 

給我NO錯誤與純Python。

Pony ORM: JSON Support in Databases
For storing JSON in the database Pony uses the following types:

SQLite - TEXT 
    PostgreSQL - JSONB (binary JSON) 
    MySQL - JSON (binary JSON, although it doesn’t have ‘B’ in the name) 
    Oracle - CLOB 

Starting with the version 3.9 SQLite provides the JSON1 extension module. This extension improves performance when working with JSON queries, although Pony can work with JSON in SQLite even without this module.

+0

因此,將該行更改爲'.order_by(lambda p:int(p.body ['age']))'導致Pony引發異常:「TypeError:Function'int'不能用於這種方式:int(p.body ['age'])」 – freebie

+0

它似乎在使用select語句時表現自己,例如'select(lambda p:p.body ['age']> 1)' - 如在Pony文檔中。這讓我覺得這是一個錯誤。但是,我沒有通過github問題頁面進行確認。 – freebie

+0

@freebie:更新了我的答案 – stovfl