django加入了两个独特的外键

时间:2014-04-28 08:10:24

标签: mysql sql django join

我坚持这个。我有两张表:

TABLE1 (CODE,SUBCODE,DESCR,FIELD4,FIELD5,...)

TABLE2 (ID1,ID2,CODE,SUBCODE,FIELD5,FIELD6,...)

和这样的模型:

class Table1(models.Model):

    code = models.IntegerField(primary_key=True, db_column='CODE') # Field name made lowercase.

    subcode = models.IntegerField(primary_key=True, db_column='SUBCODE') # Field name made lowercase.

    description = models.CharField(db_column='DESCR', max_length=30) # Field name made lowercase.

    field4 = models.CharField(db_column='FIELD4', max_length=8) # Field name made lowercase.

    field5 = models.CharField(db_column='FIELD5', max_length=30) # Field name made lowercase.

    (...)

class Meta:

    managed = False

    db_table = 'TABLE1'

    unique_together = (("code", "subcode"),)


class Table2(models.Model):

    id1 = models.IntegerField(primary_key=True, db_column='ID1') # Field name made lowercase.

    id2 = models.IntegerField(primary_key=True, db_column='ID2') # Field name made lowercase.

    code = models.IntegerField(db_column='CODE') # Field name made lowercase.<br/><br/>
    subcode = models.IntegerField(db_column='SUBCODE') # Field name made lowercase.

    field5 = models.CharField(db_column='FIELD5', max_length=32) # Field name made lowercase.

    field6 = models.FloatField(db_column='FIELD6') # Field name made lowercase.

    code_fk = models.ForeignKey(Table1, db_column='CODE', to_field='code',       related_name='code_fk')

    subcode_fk = models.ForeignKey(Table1, db_column='SUBCODE', to_field='subcode', related_name='subcode_fk')

class Meta:

    managed = False

    db_table = 'TABLE2'

    unique_together = (("id1", "id2"),)

如果我像这样做一个简单的检索:

Table2.objects.all()

有一种方法可以在模板中显示返回字段代码,子代码和从另一个表中获取的相关描述的每一行吗?

基本上我想做一个简单的

SELECT B.CODE, B.SUBCODE, A.DESCR
FROM TABLE1 A JOIN TABLE2 B
ON A.CODE = B.CODE AND A.SUBCODE = B.SUBCODE

如何修改我的模型呢?

1 个答案:

答案 0 :(得分:0)

Django does not yet support multi-column primary keys ...意味着您的模型上只有一个字段应标记为primary_key=True

如果您无法使您的数据库架构适应Django(由于您有managed=False我猜测可能是您的情况),这会出现问题

您可以尝试使用这样的模块:
https://github.com/simone/django-compositekey
(我没有亲自尝试过)