SQLAlchemy with multiple primary keys does not automatically set any

时间秒杀一切 提交于 2019-12-13 12:09:51

问题


I had a simple table:

class test(Base):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    title = Column(String)

    def __init__(self, title):
        self.title = title

When using this table, id was set automatically. I want to add another field that is unique and efficient to search, so I added the field:

id2 = Column(String, primary_key=True)

And updated the constructor:

def __init__(self, id2, title):
    self.id2 = id2
    self.title = title

Now, id is no longer automatically set, or rather I get the error:

IntegrityError: (IntegrityError) test.id may not be NULL u'INSERT INTO test (id2, title) VALUES (?, ?)' [u'a', u'b']

Is there a way to maintain a second primary key without removing the autoincrement behavior of the first?


回答1:


I have few problems here

1) What is a purpose of your hand-made __init__? If it does just what you wrote, you can omit constructor completely since SQLAlchemy machinery generates exactly the same constructor for all your models automagically. Although if you take some additional actions and thus have to override __init__ you probably want to call super-constructor:

def __init__(self, lalala, *args, **kwargs):
   # do something with lalala here...
   super(test, self).__init__(*args, **kwargs)
   # ...or here

2) Once you have more than one field with primary_key=True you get a model with composite primary key. Composite primary keys are not generated automatically since there is ambiguity here: how should subsequent key differ from previous?

I suspect what you're trying can be achieved using unique indexed column and not using composite key:

class test(Base):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    id2 = Column(String, index=True, unique=True)
    title = Column(String)

    # def __init__(self) is not necessary


来源:https://stackoverflow.com/questions/2415842/sqlalchemy-with-multiple-primary-keys-does-not-automatically-set-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!