使用字符串数据类型作为主键的SQLAlchemy

2024-06-01 01:50:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用SQLAlchemy的ORM层(通过Flask SQLAlchemy==2.0),我需要支持(摄取和更新)一些以字符串(Varchars)作为主键创建的表。顺便说一句,我在开发期间使用SQLite作为后端,但是生产数据存储将是Oracle。在

下面的代码应该创建模型,然后test_setup函数应该初始化一些测试数据,但我似乎只能创建以整数为主键的表。在

# MODEL
class MAG_BAG(db.Model):
    """An entity used for the test_setup"""
    __tablename__ = 'DS_MAG_BAG'
    BAG_ABBREV = db.Column(db.String(18), primary_key=True)
    BAG_NM = db.Column(db.String(128))
    MAGIC_POWER_DESCR = db.Column(db.String(128))
    SORT_ORD = db.Column(db.Integer)

    def __repr__(self):
        return '<MAG_BAG {0}>'.format(self.BAG_NM)

def test_setup():
    """Only used during development or testing as a convenience."""
    db.create_all() # why this no make DS_MAG_BAG?
    #
    if User.query.filter_by(login_id='felix').first() is None:
        u = User.register('felix', 'cat')
        e = Entity.register('Magic Bag', 'DS_MAG_BAG', u.id)
        # u and e populate tables just fine
        # but section below does nothing 
        for b in [('FSH','Magic Fish Sack'),('CANBAG','Canoe Bag'),('ESC', 'Escalator Bag')]:
            print(a_bag)
            a_bag = MAG_BAG(BAG_ABBREV=b[0], BAG_NM=b[1])
            db.session.add(a_bag)
            db.session.commit()

是否可以使用非数值类型的数据类型来创建表?在


Tags: testfordbstringsqlalchemysetupdscolumn