使用PonyORM

时间:2019-05-26 11:00:33

标签: python mysql ponyorm

我正在为团队合作游戏库构建API。这些游戏具有定义的属性,例如类型,大小和长度,我正在存储多对多关系。该模型如下所示:

class Game(db.Entity):
    game_type = Set('Type')
    game_length = Set('Length')
    group_size = Set('GroupSize')
    ...

class Type(db.Entity):  # similar for Length, GroupSize
    game = Set(Game)
    short = Required(str)
    full = Required(str)

它们使用不同的类型/长度/大小值填充,然后分配给不同的游戏。效果很好。

我很难弄清楚如何让数据库用户查询例如其中两个与第三个未给出。例如,我希望所有游戏都使用type=race AND size=medium而不是length=None

我之前在SQL中使用子查询和空字符串构建了该库。这是我第一次使用PonyORM:

def get_all_games(**kwargs):
    game_type = kwargs.get('game_type', None)
    group_size = kwargs.get('group_size', None)
    game_length = kwargs.get('game_length', None)

    query = select((g, gt, gs, gl) for g in Game
                                     for gt in g.game_type
                                       for gs in g.group_size
                                         for gl in g.game_length)

    if game_type:
        query = query.filter(lambda g, gt, gs, gl: gt.short == game_type)
    if group_size:
        query = query.filter(lambda g, gt, gs, gl: gs.short == group_size)
    if game_length:
        query = query.filter(lambda g, gt, gs, gl: gl.short == game_length)

    query = select(g for (g, gt, gs, gl) in query)

    result = []

    for g in query:
        this_game = get_game(g)
        result.append(this_game)

    return result

对我来说似乎太复杂了。没有元组打包和拆包的方法吗?也许可以在查询中立即使用变量,而不使用if语句?

1 个答案:

答案 0 :(得分:1)

您可以在exists中使用infilter。您也可以使用attribute lifting来简化复杂的联接:

query = Game.select()

if game_length:
    # example with exists
    query = query.filter(lambda g: exists(
        gl for gl in g.game_length
        if gl.min <= game_length and gl.max >= game_length))

if group_size:
    # example with in
    query = query.filter(lambda g: group_size in (
        gs.value for gs in g.group_sizes))

if game_type:
    # example with attribute lifting
    query = query.filter(lambda g: game_type in g.game_types.short)