Python django中的复合主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28712848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Composite primary key in django
提问by khajvah
I have a legacy db table which has composite primary key. I don't think I will be able to change the structure to include a surrogate key, as there is some code written that uses that table. And in django, I cannot use that table, as it doesn't have a primary key(non-composite).
我有一个具有复合主键的旧数据库表。我认为我无法更改结构以包含代理键,因为编写了一些使用该表的代码。在 Django 中,我无法使用该表,因为它没有主键(非复合键)。
Do django models support composite primary keys? If not, is there any workaround without changing the structure of the table?
django 模型是否支持复合主键?如果没有,是否有任何解决方法而不更改表的结构?
P.S. I am using postgresql.
PS我正在使用postgresql。
采纳答案by M.javid
Try similar below code:
尝试类似下面的代码:
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField(primary_key=True)
key2 = models.IntegerField()
or if you want only unique mixed fields:
或者如果您只想要唯一的混合字段:
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField()
key2 = models.IntegerField()
EDIT: I would like to note that there is a problem with this approach if there are 3 columns. Update queries don't work because it tries to update (puts pk fields right after "SET") the fields that are unique together and obviously fails.
编辑:我想指出,如果有 3 列,则这种方法存在问题。更新查询不起作用,因为它试图更新(将 pk 字段放在“SET”之后)唯一的字段,但显然失败了。