Take the 2-minute tour ×

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer

Your Answer


