复合主键在django [英] Composite primary key in django

查看:127
本文介绍了复合主键在django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有复合主键的旧数据库表。我不认为我将能够将结构更改为包含代理键,因为有一些使用该表的代码。而在django中,我不能使用该表,因为它没有主键(非复合)。



django模型是否支持复合主键?如果没有,是否有任何解决方法,而不改变表的结构?



我正在使用postgresql。

解决方案

请尝试类似以下代码:

  class MyTable(models.Model):
class Meta:
unique_together =(('key1','key2'),)

key1 = models.IntegerField(primary_key = True)
key2 = models.IntegerField()

或者如果您只想要唯一的混合字段:

  class MyTable(models.Model):
class Meta:
unique_together =(('key1','key2'),)

key1 = models.IntegerField()
key2 = models.IntegerField()

编辑:我想注意,如果有3列,这种方法有一个问题。更新查询不起作用,因为它尝试更新(在SET之后放置pk字段)唯一的字段,显然失败。


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).

Do django models support composite primary keys? If not, is there any workaround without changing the structure of the table?

P.S. I am using postgresql.

解决方案

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.

这篇关于复合主键在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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