我正在使用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中这等效于什么?
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有一个示例。
在转换中,您似乎错过了主键和外键规范。