How to define a table without primary key with SQLAlchemy?

前端 未结 4 456
忘了有多久
忘了有多久 2021-01-17 07:09

I have a table that does not have a primary key. And I really do not want to apply this constraint to this table.

In SQLAlchemy, I defined the

相关标签:
4条回答
  • 2021-01-17 07:57

    There is only one way that I know of to circumvent the primary key constraint in SQL Alchemy - it's to map specific column or columns to your table as a primary keys, even if they aren't primary key themselves. http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key.

    0 讨论(0)
  • 2021-01-17 07:59

    The solution I found is to add an auto-incrementing primary key column to the table, then use that as your primary key. The database should deal with everything else beyond that.

    0 讨论(0)
  • 2021-01-17 08:12

    There is no proper solution for this but there are workarounds for it:

    Workaround 1

    Adding parameter primary_key to the existing column that is not having a primary key will work.

    class SomeTable(Base):
        __table__ = 'some_table'
        some_other_already_existing_column = Column(..., primary_key=True) # just add primary key to it whether or not this column is having primary key or not
    

    Workaround 2

    Just declare a new dummy column on the ORM layer, not in actual DB. Just define in SQLalchemy model

    class SomeTable(Base):
        __table__ = 'some_table'
        column_not_exist_in_db = Column(Integer, primary_key=True) # just add for sake of this error, dont add in db
    
    0 讨论(0)
  • 2021-01-17 08:13

    Disclaimer: Oracle only

    Oracle databases secretly store something called rowid to uniquely define each record in a table, even if the table doesn't have a primary key. I solved my lack of primary key problem (which I did not cause!) by constructing my ORM object like:

    class MyTable(Base)
        __tablename__ = 'stupid_poorly_designed_table'
        
        rowid = Column(String, primary_key=True)
        column_a = Column(String)
        column_b = Column(String)
        ...
    

    You can see what rowid actually looks like (it's a hex value I believe) by running

    SELECT rowid FROM stupid_poorly_designed_table
    GO
    
    0 讨论(0)
提交回复
热议问题