ManyToMany过滤器不能正常工作Django

时间:2017-08-31 18:53:05

标签: python django oracle django-models

我有以下型号

class A(models.Model)
    a_id = models.IntegerField(primary_key=True)
    created_by_id = models.ManyToManyField(User,db_column="user_id", related_name="created_by_id")
    last_updated_by = models.ManyToManyField(User, db_column="user_id", related_name="last_updated_by",)
    resolved_by_id = models.ManyToManyField(User, db_column="user_id", related_name='resolved_by_id')

class B(models.Model):
    ....

class C(models.Model):
    ....

class User(models.Model):
    user_id = models.IntegerField(primary_key=True)
    user_name = models.CharField(max_lenght=30)

    field_1 = models.ForeignKey(B)
    field_2 = models.ForeignKey(C)

当我在class A上应用序列化时,我在SQL表中找不到以下错误,我使用的是OracleDB

ORA-00942: table or view does not exist

('SELECT "USER"."USER_ID", "USER"."USER_NAME" FROM "USER" INNER '
 'JOIN "A_CREATED_BY_ID" ON ("USER"."USER_ID" = '
 '"A_CREATED_BY_ID"."USERMST") WHERE '
 '"A_CREATED_BY_ID"."A_ID" = %s')

我已经查看过ManytoMany的Django文档仍然无法弄清问题是什么。

更新:这是旧版数据库,我们没有使用迁移

1 个答案:

答案 0 :(得分:1)

由于这是一个遗留数据库,Django没有创建表,因此不了解ManyToManyFields使用的中间表。你必须让Django知道它应该用于连接的表。 例如:

created_by_id = models.ManyToManyField(
    User,
    through="ModelName" # the model name
    db_table="table_name" # the table name in the DB for the join
    db_column="user_id", # this one you could drop
    related_name="created_by_id"
)

您应该在模型中指定连接A类和用户类的db_column

您还可以将class Meta添加到模型中:

class Meta:
    managed = False

对于每个阅读代码的人来说,显而易见的是数据库不是由Django管理的。

编辑: 以下是有关选项through的官方文档的link