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

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

问题描述

我有一个具有复合主键的旧数据库表.我认为我无法更改结构以包含代理键,因为编写了一些使用该表的代码.在 Django 中,我不能使用该表,因为它没有主键(非复合键).

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?

附言我正在使用 postgresql.

P.S. I am using postgresql.

推荐答案

试试下面类似的代码:

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

我想指出,如果有 3 列,则此方法存在问题.更新查询不起作用,因为它试图更新(将 pk 字段放在SET"之后)那些唯一的字段,但显然失败了.

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天全站免登陆