【问题标题】:App engine NDB make_key alternative in Python SqlAlchemyPython SqlAlchemy 中的应用引擎 NDB make_key 替代方案
【发布时间】:2019-11-21 21:25:58
【问题描述】:

我正在使用 Python(3.7) 和 Flask 开发一个项目。我正在从 Google App Engine Webapp2 传输一个应用程序,其中模型已使用 NDB 实现,因此我需要将这些模型转换为 SqlAlchemy 模型。我在模型类中发现了一个make_key 方法,我不知道它们到底是什么,那么如何将其转换为 SqlAlchemy 模型。

以下是来自NDB 的一些模型示例:

class Groupvalue(ndb.Model):
    """A main model for representing an individual Guestbook entry."""
    value = ndb.StringProperty()
    rank = ndb.IntegerProperty(default=1)
    username = ndb.StringProperty()

    @classmethod
    def make_key(cls, isbn):
        return ndb.Key(cls, isbn)

class LoxonValues(ndb.Model):
    """A main model for representing an individual Guestbook entry."""
    value = ndb.StringProperty()
    score = ndb.StringProperty()
    rank = ndb.IntegerProperty(default=1)
    username = ndb.StringProperty()
    group = ndb.StringProperty(default='notingroup')
    date = ndb.DateTimeProperty(auto_now_add=True)

    @classmethod
    def make_key(cls, isbn):
        return ndb.Key(cls, isbn)

以下是我将这些模型转移到 Python-SqlAlchemy 中的方法:

class Groupvalue(db.Model):
    value = db.Column(db.String())
    rank = db.Column(db.Integer(default=1))
    username = db.Column(db.String())


class LoxonValues(db.Model):
    value = db.Column(db.String())
    score = db.Column(db.String())
    rank = db.Column(db.Integer(default=1))
    username = db.Column(db.String())
    group = db.Column(db.String(default='notingroup'))
    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)

我对 make_key 模型中使用的 make_key 方法感到困惑,这在 SqlAlchemy 中的等价物是什么?

【问题讨论】:

  • 这是否意味着您正在将数据库从 ndb 迁移到基于 sql 的解决方案?
  • 是的,你是对的!

标签: python google-app-engine sqlalchemy flask-sqlalchemy app-engine-ndb


【解决方案1】:

sqlalchemy 中不需要make_key()。相反,您将列标记为主键。

来自nbd/key.py

A key [is a]...

* a list of one or more ``(kind, id)`` pairs where ``kind`` is a string
  and ``id`` is either a string or an integer
...

The last ``(kind, id)`` pair gives the kind
and the ID of the entity that the key refers to, the others merely
specify a "parent key".

The kind is a string giving the name of the model class used to
represent the entity. In more traditional databases this would be
the table name. A model class is a Python class derived from
:class:`.Model`. Only the class name itself is used as the kind. This means
all your model classes must be uniquely named within one application. You can
override this on a per-class basis.

The ID is either a string or an integer. When the ID is a string, the
application is in control of how it assigns IDs. For example, you
could use an email address as the ID for Account entities.

...

关系数据库不是分层的,即没有[(kind,id),...] 键, 而是一个主键来处理平面表中的条目。 这个post 有一个例子。

在您的转换中,您似乎错过了主键和外键规范。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多