具有多个主键的SQLAlchemy不会自动设置任何 [英] SQLAlchemy with multiple primary keys does not automatically set any

查看:182
本文介绍了具有多个主键的SQLAlchemy不会自动设置任何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表:

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

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

使用此表时,会自动设置ID。我想添加另一个唯一且有效的搜索字段,所以我添加了该字段:

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)

并更新了构造函数:

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

现在,不再自动设置id,或者我收到错误消息:

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

IntegrityError:(IntegrityError)test.id不能为NULL u'INSERT INTO test(id2,title)VALUES(?,?)'[u'a',u'b']

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?

推荐答案

I这里有几个问题

1)手工制作的 __ init __ 的目的是什么?如果它只是您编写的内容,则可以完全省略构造函数,因为SQLAlchemy机制自动为所有模型生成完全相同的构造函数。尽管如果您采取一些其他措施并因此不得不覆盖 __ init __ ,则可能要调用超级构造函数:

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)如果使用 primary_key = True 有多个字段,则可以得到带有复合主键的模型。复合主键不会自动生成,因为这里存在歧义:后续键与以前的键有什么区别?

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

这篇关于具有多个主键的SQLAlchemy不会自动设置任何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆