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
发布评论