0

我不太清楚如何在遗留数据库中处理多对多关系。

模型.py:

class Trecho(models.Model):
    cod = models.BigIntegerField(primary_key=True)
    torres = models.ManyToManyField('Torre', through="Trecho_Com_Torre")

    class Meta:
        managed = False
        db_table = 'OPE_TRECHO'

class Torre(models.Model):
    cod = models.BigIntegerField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'OPE_TO'

class Trecho_Com_Torre(models.Model):
    cod = models.BigIntegerField(primary_key=True)
    cod_trecho = models.ForeignKey('Trecho', on_delete=models.CASCADE, db_index=False, db_column='COD_TRECHO')
    cod_to = models.ForeignKey('Torre', on_delete=models.CASCADE, db_index=False, db_column='COD_TO')

    class Meta:
        managed = False
        db_table = 'OPE_TRECHO_COM_TO'

当我尝试运行以下查询时,错误是“Torre 对象没有属性 trecho__set”:

t1 = Torre.objects.get(cod=1)
trechos = t1.trecho__set.all()

如果我没记错的话,如果所有这些表都是由 Django 管理的,这将起作用,但由于它们是遗留的,我怎样才能使它工作?

4

0 回答 0