模型中的自动 GUID key_name

发布于 2024-12-18 04:51:26 字数 297 浏览 2 评论 0原文

我希望我的模型自动获取 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 技术交流群。

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

发布评论

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

评论(2

勿忘初心 2024-12-25 04:51:26

Model 子类上重写 __init__ 是危险的,因为构造函数除了被用户代码使用之外,还被框架用来从数据存储中重建实例。除非您确切地知道如何使用构造函数来重建现有实体(这是内部细节并且将来可能会发生变化),否则您应该避免覆盖它。

相反,定义一个工厂方法,如下所示:

class MyModel(db.Model):
  @classmethod
  def new(cls, **kwargs):
    return cls(key_name=str(uuid.uuid4()), **kwargs)

Overriding __init__ on a Model 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:

class MyModel(db.Model):
  @classmethod
  def new(cls, **kwargs):
    return cls(key_name=str(uuid.uuid4()), **kwargs)
甚是思念 2024-12-25 04:51:26

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文