开发者

Is it possible to dynamically name attributes in an App Engine Model?

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?


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


This SO question:

  • Adding a user supplied property (at runtime) to an instance of Expando class in google app engine?

gives an example of what you want to do.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜