SQLAlchemy with multiple primary keys does not install automatically

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, the identifier was set automatically. I want to add another field that is unique and efficient to search, so I added a 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 set automatically, or rather, I get an error:

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

Is there a way to save the second primary key without deleting the auto-increment behavior of the first?

+3
source share
1 answer

.

1) __init__? , , , SQLAlchemy . , , , __init__, , , -:

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

2) primary_key=True, . , : ?

, , :

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
+7

Source: https://habr.com/ru/post/1736274/


All Articles