2016-11-11 59 views
0

我用peewee相關與exsits表:如何根據定義的Jsonfield判斷一個元素是否在列表中?

import peewee 
from playhouse.postgres_ext import * 
class Rules(peewee.Model): 
    channels = JSONField(null=True) 
    remark = peewee.CharField(max_length=500, null=True) 
    class Meta: 
     database = db 
     db_table = 'biz_rule' 
     schema = 'opr' 

例如:在我的表中存在的列頻道的記錄:

["A012102","C012102","D012102","E012102"] 

我想判斷「A012102」是否在名單,如何編寫代碼?

回答

0

如果您使用的是PostgreSQL 9.4+,則可以使用jsonb數據類型,使用相應的postgres_ext.BinaryJSONField peewee字段類型。它有contains_any()contains_all()方法,它們對應於PostgreSQL ?|?&運算符(see the PostgreSQL JSON docs)。所以我認爲它會是這樣的:

from playhouse.postgres_ext import BinaryJSONField 

class Rules(peewee.Model): 
    channels = BinaryJSONField(null=True) 
    ... 

query = Rules.select().where(Rules.channels.contains_all('A012102')) 
相關問題