Python MongoDB动态查询构建具有多种条件

时间:2017-10-01 23:21:16

标签: python mongodb flask flask-pymongo

我正在使用flask_pymongo构建一个开源项目,Python MongoDB ORM(特别是针对Flask),我很擅长构建动态条件。

下面的代码就是我在相应的文件中写的

Model.py

from app.database import Database

class Model:

    conditions = {"and":[], "or":[], "in":[]}
    operators = {
        "!=": "$ne",
        "<": "$lt",
        ">": "$gt",
        "<=": "$lte",
        ">=": "$gte",
        "in": "$in",
        "not in":"$nin",
        "and": "$and",
        "or": "$or"
    }

    def __init__(self):
        # collection property from User class
        # Database class takes collection to fire MongoDB queries 
        self.db = Database(self.collection)

    def where(self, field, operator, value=None):
        if value is None:
            # to enable Model.where("first_name", "John")
            value = operator
            operator = "="

        self._handle_condition("and", field, operator, value)
        # to enable Model.where().where_or() and etc
        return self

    def where_or(self, field, operator, value=None):
        if value is None:
            # to enable Model.where("first_name", "John")
            value = operator
            operator = "="

        self._handle_condition("or", field, operator, value)
        # to enable Model.where().where_or() and etc
        return self

   def _handle_condition(self, type, field, operator, value):
        self.conditions[type].append({"field":field, "operator":operator, value:value})

   def get(self):
       filetrs = {}
       for type in self.conditions:
           filetrs[self.operators[type]] = []
           for condition in self.conditions[type]:
               if condition["operator"] == "=":
                   filter = {condition["field"]:condition["value"]}
               else:
                   filter = {condition["field"]:{self.operators[condition["operator"]]:condition["value"]}}
               filetrs[self.operators[type]].append(filter)
       return self.db.find(filters)

User.py

from app.Model import Model

class UserModel(Model):
    # MongoDB collection name
    collection = "users"

    def __init__(self):
        Model.__init__(self)

User = UserModel()

我希望实现的目标是UserController.pyUser.py导入并使用where,就像上面提到的代码一样。

使用where_orget模型方法添加多个条件时,find方法正在解析所有条件并将其作为过滤器传递给from app.User import User class UserController: def index(self): # Should return all the users where _id is not blank or their first_name is equal to John return User.where("_id", "!=", "").where_or("first_name", "John").get() 方法

UserController.py

where

问题是它应该不起作用,它似乎适用于任何一个条件,where_orwhere,但当我尝试添加多个where_or和{{ 1}}条件不起作用。

非常感谢您的帮助。

PS:这个问题似乎有很多代码,但为了让您了解我必须完成的完整方案,如果您仍需要任何澄清,请随时发表评论。

热切期待。

0 个答案:

没有答案