How to use Django with legacy readonly database tables with composite primary keys?

*爱你&永不变心* 提交于 2019-12-01 11:46:31

You are talking about a legacy READONLY database then, perhaps you can create an external schema (views) with no multi-column PKs. For example you can concatenate field keys. Here and example:

For example:

Tables:

create table A (
  a1 int not null,
  a2 int not null,
  t1 varchar(100),
  primary key (a1, a2)
)

create table B (
  b1 int not null,
  b2 int not null,
  a1 int not null,
  a2 int not null,
  t1 varchar(100),
  primary key (b1, b2),
  constraint b_2_a foreign key (a1,a2) 
  references A (a1, a2)
)

External schema to be read by django:

Create view vA as 
select 
   a1* 1000000 + a2 as a, A.* 
from A

Create view vB as 
select 
   b1* 1000000 + b2 as b, 
   a1* 1000000 + a2 as a, B.* 
from B

django models:

class A(models.Model):
    a = models.IntegerField(  primary_key=True )
    a1 = ...
    class Meta(CommonInfo.Meta):
        db_table = 'vA'    

class B(models.Model):
    b = models.IntegerField(  primary_key=True )
    b1 = ...
    a = models.ForeignKey( A )
    a1 = ...
    class Meta(CommonInfo.Meta):
        db_table = 'vB'    

You can refine technique to make varchar keys to be able to work with indexes. I don't write more samples because I don't know what is your database brand.

More information:

Do Django models support multiple-column primary keys?

ticket 373

Alternative methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!