Python 与 MongoEngine - 访问自定义模型属性列表

标签 python mongodb inheritance copy

正在寻找轻松访问我拥有的一些 Python 模型类中的自定义模型属性列表的方法。我使用 MongoEngine 作为我的 ORM,但问题是一般继承和 OOP。

具体来说,我希望能够从 Mixin 类中的方法访问自定义模型属性,我将在所有模型类中继承该类。

考虑以下类结构:

class ModelMixin(object):
    def get_copy(self):
        """
        I'd like this to return a model object with only the custom fields
        copied.  For the City object below, it would run code equivalent to:

          city_copy = City()
          city_copy.name = self.name
          city_copy.state = self.state
          city_copy.popluation = self.population
          return city_copy

        """


class City(BaseModel, ModelMixin):
    name = orm_library.StringField()
    state = orm_library.StringField()
    population = orm_library.IntField()

这将允许以下操作:

>>> new_york = City(name="New York", state="NY", population="13000000")
>>> new_york_copy = new_york.get_copy()

但是,它必须适用于任意模型。不知何故,它必须确定子类中定义了哪些自定义属性,实例化该子类的实例,并仅复制那些自定义属性,而无需从父 BaseModel 类(其具有其中有大量我不关心的随机内容。

有人知道我该怎么做吗?

最佳答案

我认为您可以使用多种工具来实现这一目标 (如果我下面的代码不能完全满足您的要求,您应该 能够很容易地适应它)。即:

<小时/>
class ModelMixin(object):
    def get_copy(self):

        # Get the class for the 

        C = self.__class__

        # make a new copy

        result = C()

        # iterate over all the class attributes of C
        # that are instances of BaseField

        for attr in [k for k,v in vars(C).items() if v.__class__ == BaseField]:
            setattr(result, attr, getattr(self, attr))

        return result

测试上述内容(为 MongoEngine 模型/字段创建虚拟类)

class BaseField(object):
    pass

class BaseModel(object):
    baseField = BaseField()

class City(BaseModel, ModelMixin):
    x = BaseField()
    y = BaseField()

c = City()
c.x = 3
c.y = 4
c.baseField = 5

d = c.get_copy()
print d.x # prints '3'
print d.y # prints '4'
print d.baseField # correctly prints main.BaseField, because it's not set for d

关于Python 与 MongoEngine - 访问自定义模型属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15007867/

相关文章:

python - py2exe 和 pyinstaller 生成的 exe 不起作用

php - 将命令从 PHP 传递到 Python

python - 在一系列python文件中运行主文件是否有标准?

mongodb - 获取字段 Morphia 的最大值

java - 继承的构造函数java : Call to super() must be first statement

c++ - 模板继承 : Symbol not found

python - 通过 Windows 控制台使用 Docker : includes invalid characters $PWD for a local volume name

mongodb - 元组(数组)作为 mongoose.js 中的属性

c# - 如何更新 mongodb 中除指定字段之外的所有文档字段

派生类的 C++ 构造函数,其中基类包含类成员