SQLAlchemy多个主键未自动设置任何值
我有一个简单的表格:
class test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title = title
在使用这个表格的时候,id字段是自动生成的。我想添加一个新的字段,这个字段需要是唯一的,并且方便搜索,所以我添加了这个字段:
id2 = Column(String, primary_key=True)
然后我更新了构造函数:
def __init__(self, id2, title):
self.id2 = id2
self.title = title
现在,id字段不再自动生成了,或者说我遇到了这个错误:
IntegrityError: (IntegrityError) test.id 不能为 NULL u'INSERT INTO test (id2, title) VALUES (?, ?)' [u'a', u'b']
有没有办法在不去掉第一个字段自动增加功能的情况下,保持第二个主键的存在呢?
1 个回答
7
我这里有几个问题
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