模型中的自动 GUID key_name
我希望我的模型自动获取 GUID 作为 key_name,我正在使用下面的代码。这是解决问题的好方法吗?它有什么缺点吗?
class SyncModel(polymodel.PolyModel):
def __init__(self, key_name=None, key=None, **kwargs):
super(SyncModel, self).__init__(key_name=str(uuid.uuid1()) if not key else None,key=key, **kwargs)
I want my model to get a GUID as key_name automatically and I'm using the code below. Is that a good approach to solve it? Does it have any drawbacks?
class SyncModel(polymodel.PolyModel):
def __init__(self, key_name=None, key=None, **kwargs):
super(SyncModel, self).__init__(key_name=str(uuid.uuid1()) if not key else None,key=key, **kwargs)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
Model
子类上重写__init__
是危险的,因为构造函数除了被用户代码使用之外,还被框架用来从数据存储中重建实例。除非您确切地知道如何使用构造函数来重建现有实体(这是内部细节并且将来可能会发生变化),否则您应该避免覆盖它。相反,定义一个工厂方法,如下所示:
Overriding
__init__
on aModel
subclass is dangerous, because the constructor is used by the framework to reconstruct instances from the datastore, in addition to being used by user code. Unless you know exactly how the constructor is used to reconstruct existing entities - something which is an internal detail and may change in future - you should avoid overriding it.Instead, define a factory method, like this:
Nick 有一篇关于 pre 和 post put 挂钩 用于设置 key_name,我不知道如果您当前的方法有效或无效,但至少您应该了解其他选项。
There is an article by Nick about pre and post put hooks which and be used to set the key_name, I don't know if your current method is valid or not but at least you should be aware of other options.