【问题标题】:Create Column with Array of Model Class type in SqlAlchemy在 SqlAlchemy 中创建具有模型类类型数组的列
【发布时间】:2021-05-01 14:03:43
【问题描述】:

我正在尝试使用 SQLAlchemy 创建一个 Order 模型,其中包含一个定义了 ProductItem 类数组的列,但它引发了异常 这两个类都定义在同一个文件中

models.py

# Product Item Class
class ProductItem(Base):
    __tablename__ = 'product_items'
    id = Column(Integer, primary_key=True, index=True)
    productName = Column(String,index=True,nullable=False)
    productBrand = Column(String, nullable=False)
    
    def __repr__(self):
        return "<ProductList(productName = '%s', productCategoryName = '%s')>" % (
            self.productName,
            self.productCategoryName
        )

#Order Class
class Order(Base):
    __tablename__ = 'orders'
    id= Column(Integer, index=True, primary_key=True)
    dateCreated = Column(DateTime,nullable=False)
    dateDelivered = Column(DateTime, nullable=True)
    orderItem = Column(ARRAY(ProductItem), nullable=False)  # This Column
    orderStatus = Column(String, nullable=False)

例外:

>alembic revision --autogenerate -m "Initial db with order"
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added table 'orders'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_orders_businessId' on '['businessId']'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_orders_customerId' on '['customerId']'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_orders_id' on '['id']'
INFO  [alembic.ddl.postgresql] Detected sequence named 'product_categories_id_seq' as owned by integer column 'product_categories(id)', assuming SERIAL and omitting
INFO  [alembic.ddl.postgresql] Detected sequence named 'business_billing_id_seq' as owned by integer column 'business_billing(id)', assuming SERIAL and omitting
INFO  [alembic.ddl.postgresql] Detected sequence named 'business_timings_id_seq' as owned by integer column 'business_timings(id)', assuming SERIAL and omitting
INFO  [alembic.ddl.postgresql] Detected sequence named 'product_items_id_seq' as owned by integer column 'product_items(id)', assuming SERIAL and omitting
INFO  [alembic.ddl.postgresql] Detected sequence named 'inventory_id_seq' as owned by integer column 'inventory(id)', assuming SERIAL and omitting
Generating D:\app Backend\db-migration\versions\ceff7117b4cb_initial_db_without_order.py ...  done
Traceback (most recent call last):
  File "c:\users\mahesh\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\mahesh\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "D:\app Backend\env\Scripts\alembic.exe\__main__.py", line 7, in <module>
  File "d:\app backend\env\lib\site-packages\alembic\config.py", line 559, in main
    CommandLine(prog=prog).main(argv=argv)
  File "d:\app backend\env\lib\site-packages\alembic\config.py", line 553, in main
    self.run_cmd(cfg, options)
  File "d:\app backend\env\lib\site-packages\alembic\config.py", line 530, in run_cmd
    fn(
  File "d:\app backend\env\lib\site-packages\alembic\command.py", line 219, in revision
    scripts = [script for script in revision_context.generate_scripts()]
  File "d:\app backend\env\lib\site-packages\alembic\command.py", line 219, in <listcomp>
    scripts = [script for script in revision_context.generate_scripts()]
  File "d:\app backend\env\lib\site-packages\alembic\autogenerate\api.py", line 533, in generate_scripts
    yield self._to_script(generated_revision)
  File "d:\app backend\env\lib\site-packages\alembic\autogenerate\api.py", line 449, in _to_script
    return self.script_directory.generate_revision(
  File "d:\app backend\env\lib\site-packages\alembic\script\base.py", line 658, in generate_revision
    script = Script._from_path(self, path)
  File "d:\app backend\env\lib\site-packages\alembic\script\base.py", line 851, in _from_path
    return cls._from_filename(scriptdir, dir_, filename)
  File "d:\app backend\env\lib\site-packages\alembic\script\base.py", line 904, in _from_filename
    module = util.load_python_file(dir_, filename)
  File "d:\app backend\env\lib\site-packages\alembic\util\pyfiles.py", line 97, in load_python_file
    module = load_module_py(module_id, path)
  File "d:\app backend\env\lib\site-packages\alembic\util\compat.py", line 182, in load_module_py
    spec.loader.exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 786, in exec_module
  File "<frozen importlib._bootstrap_external>", line 923, in get_code
  File "<frozen importlib._bootstrap_external>", line 853, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "D:\App Backend\db-migration\versions\ceff7117b4cb_initial_db_without_order.py", line 25
    sa.Column('orderItem', sa.ARRAY(app.models.<app.models.ProductItem object at 0x00000256DF9ED100>), nullable=False),
                                                  ^
SyntaxError: invalid syntax

搜索了很多,但找不到任何描述数组自定义类型的文档。我需要一种在 Order 类中存储 ProductItem 类数组的方法。任何帮助,将不胜感激。谢谢!

【问题讨论】:

    标签: python postgresql sqlalchemy model fastapi


    【解决方案1】:

    来自PostgreSQL: documentation

    PostgreSQL 允许将表的列定义为可变长度的多维数组。可以创建任何内置或用户定义的基本类型、枚举类型、复合类型、范围类型或域的数组。

    因此,您将无法创建任何 Python 类的 ARRAY 列,除非您在数据库中创建相应的 用户定义 类型,这很可能与原因相反应该如何使用 SQLAlchemy。

    您需要一种方法来创建需要关联表的Many To Many 关系。


    另请参阅this question 的答案,这是一个类似的问题,尽管它侧重于从ARRAY 数据类型强制执行ForeignKey 约束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2014-12-06
      • 2018-03-24
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多