问题
I want to use Django for a client project that has a legacy database. If at all possible I would like to be able to use the Django admin interface. However, the database has tables with multicolumn primary keys, which I see Django does not like - the admin interface throws a MultipleObjectsReturned exception.
What are the options here? I can add new tables, but I can't change existing tables since other projects are already adding data to the database. I've seen other questions mentioning surrogate keys, but it seems like that would require changing the tables.
EDIT: The database in question is a MySQL database.
回答1:
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
来源:https://stackoverflow.com/questions/7968205/how-to-use-django-with-legacy-readonly-database-tables-with-composite-primary-ke