复合主键在django

编程入门 行业动态 更新时间:2024-10-28 16:28:34
本文介绍了复合主键在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

本文发布于:2023-10-22 23:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主键   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!