gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:54 25 4
gpt4 key购买 nike

正在寻找轻松访问我拥有的一些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com