Python SqlAlchemy中的App Engine NDB make_key替代项

问题描述 投票:0回答:1

我正在使用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模型中已使用的NDB方法感到困惑,在SqlAlchemy中这等效于什么?

python google-app-engine sqlalchemy flask-sqlalchemy app-engine-ndb
1个回答
0
投票

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

来自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有一个示例。

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

© www.soinside.com 2019 - 2024. All rights reserved.