1

我正在使用flask_pymongo构建一个开源项目,Python MongoDB ORM(特别是对于 Flask),我有点坚持构建动态条件。

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

模型.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)

用户.py

from app.Model import Model

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

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

User = UserModel()

我想要实现的是,从UserController.py哪里User.py导入和使用,就像提到的代码一样。

where在使用和where_orModel 方法添加多个条件的情况下,get方法正在解析所有条件并作为过滤器传递给find方法

用户控制器.py

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()

问题是这不起作用,它似乎适用于任何一种条件,where或者where_or但是当我尝试添加多个wherewhere_or条件时它不起作用。

非常感谢您的帮助。

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

热切期待。

4

0 回答 0