是否可以在 App Engine 模型中动态命名属性?

发布于 2024-10-03 17:32:59 字数 740 浏览 4 评论 0原文

setattr 允许您动态命名 Python 类中的属性。我正在尝试对 App Engine 模型执行类似的操作:

class MyModel(db.Model):
    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)

        # Doesn't fully work
        setatr(self, 'prop1', db.ListProperty(db.Key))
        setatr(self, 'prop2', db.StringListProperty())

    # Works fully
    # prop1 = db.ListProperty(db.Key))
    # prop2 = db.StringListProperty())

此代码可以编译,但是当我稍后调用 model.prop1.append(key) 时,我收到此错误:

AttributeError: 'ListProperty' object has no attribute 'append'

我怀疑这是因为prop1 在模型中声明,而不是 self.prop1,但我不完全理解语法的意义。

有谁做到了这一点,或者有人对语法差异有任何见解吗?

setattr allows you to dynamically name attributes in Python classes. I'm trying to do something similar with an App Engine Model:

class MyModel(db.Model):
    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)

        # Doesn't fully work
        setatr(self, 'prop1', db.ListProperty(db.Key))
        setatr(self, 'prop2', db.StringListProperty())

    # Works fully
    # prop1 = db.ListProperty(db.Key))
    # prop2 = db.StringListProperty())

This code compiles, but when I call model.prop1.append(key) later on, I get this error:

AttributeError: 'ListProperty' object has no attribute 'append'

I suspect this is because prop1 is declared in models instead of self.prop1, but I don't fully understand the syntax's significance.

Has anyone accomplished this, or does anyone have any insight into syntactic differences?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我的黑色迷你裙 2024-10-10 17:32:59

我认为您正在寻找 db.Expando 类(而不是 db.Model)。

I think you're looking for the db.Expando class (instead of db.Model).

感情旳空白 2024-10-10 17:32:59

不确定,但这可能有效:

class MyModel(db.Model):
    @classmethod
    def new(cls, *args, **kwargs):        
        setattr(cls, 'props1', db.ListProperty(db.Key))
        setattr(cls, 'props2', db.StringListProperty())
        mymodel = cls(*args, **kwargs)
        delattr(cls, 'props1')
        delattr(cls, 'props2')
        return mymodel

Not sure but would this work maybe:

class MyModel(db.Model):
    @classmethod
    def new(cls, *args, **kwargs):        
        setattr(cls, 'props1', db.ListProperty(db.Key))
        setattr(cls, 'props2', db.StringListProperty())
        mymodel = cls(*args, **kwargs)
        delattr(cls, 'props1')
        delattr(cls, 'props2')
        return mymodel
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文